{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ba4dadd5",
   "metadata": {},
   "source": [
    "# 频率分析 (4)：非谐性频率矫正 VPT2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85539b2b",
   "metadata": {},
   "source": [
    "在本文档中，我们将会讨论非谐性频率矫正模型 VPT2。\n",
    "\n",
    "在量化计算中，通常分子振动的频率通过 Hessian 矩阵给出。但我们也知道，Hessian 矩阵是能量对原子核坐标的两次导数；以这种方式求得的频率，相当于求取抛物线势函数的频率。但真实的势函数并非抛物线 (譬如 Morse、L-J 势函数等)，因此真实的频率会与 Hessian 矩阵所得到的值有少许区别。这也会影响到热力学矫正中，频率配分函数所产生的贡献值。\n",
    "\n",
    "为了获得更真实的分子振动信息，那么就需要求解 Hamiltonian 受分子振动微扰后的本征波函数，并进而进行分析。近似的做法可以是微扰理论的矫正。这篇文档是其中一种近似方法，称为 Vibrational Perturbation Theory to the Second-Order (VPT2)。\n",
    "\n",
    "我们主要会依据 V. Barone [^Barone.JCP.2005] 所提供的算法与公式进行实现。我们不对公式与其正确性作推演与检查。我们主要与 Gaussian 16 rev. B01 的结果作参照，但不会完全相同。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f3aef06",
   "metadata": {},
   "source": [
    ":::{note}\n",
    "\n",
    "在 4 Core CPU 上完整执行本文档需要大约 5-10 分钟。\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5fbf2b6c",
   "metadata": {
    "raw_mimetype": "myST"
   },
   "source": [
    "::: {warning}\n",
    "\n",
    "我们在本文档中使用处于非平衡构型的非对称的氨分子。\n",
    "\n",
    "- **频率分析没有物理意义**：频率分析原则上一定要处于平衡构型；特殊的情况会是过渡态。除此之外的情况，频率分析都没有物理意义。需要先优化到稳定的构型再进行分析。\n",
    "- **不考察对称性**：对于对称的分子，有可能会产生简并的频率。在一些情况下，简并会产生数值上的奇点。非简并的分子不太容易产生奇点，分析相对容易。\n",
    "- **非线性分子**：很多时候，线性与非线性分子需要分别使用不同的方法分析。我们只考虑非线性分子，即 $3N-6$ 型分子。\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f6f47e3",
   "metadata": {},
   "source": [
    ":::{danger}\n",
    "\n",
    "若本文档有幸 (或不幸) 能帮助到读者，读者也需要知道**这份文档的程序实现未必正确！**\n",
    "\n",
    "本文档所用于计算的体系比较特别 (有虚频的氨、能量最低结构的乙醛)，**无法保证可以应用到其它的分子**。\n",
    "\n",
    "同时，**Gaussian 的不同版本有不同的 bug 和使用技巧** (当然完全可能是我的错误，但这应由读者去判断与负责)。我们会在具体的位置，给出各个版本存在潜在问题的情况；并且可能的话，会给出如何重复出 Gaussian 的结果。对于输入卡 {download}`anharm.gjf` 我们所考察的 Gaussian 版本有 16 rev. B01 {download}`anharm-G16B01.log`, 09 rev. D01 {download}`anharm-G09D01.log`, 09 rev. C01 {download}`anharm-G09C01.log`。\n",
    "\n",
    "读者特别需要注意在作性质计算时，**大多数时候我们采用 Eckart Orientation**。\n",
    "\n",
    "由于当前的 VPT2 理论本身就不适合用于小分子以外的计算 (容易由于频率共振而给出非常离谱的非谐矫正值)，因此即使看起来这里给出的做法似乎适合大分子，并且程序也看起来不会报错，但**必须要慎用当前文档所实现的 VPT2**。VPT2 有不止一种应用方式；Gaussian 也实现了一些变种，可以一定程度上解决共振效应，这是本文档我完全无法处理的。\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c8f1daf",
   "metadata": {},
   "source": [
    "VPT2 分析会稍微复杂一些。我们在这里尽管会与 Gaussian 16 的结果作对照，但所有量化计算都会在 PySCF 进行。为此我们需要对 Hessian 矩阵作基础的 [频率分析](freq_1.ipynb)，并且需要进行 [数值导数](https://py-xdh.readthedocs.io/zh_CN/latest/numdiff/nuc_grad.html)；这两个功能分别实现在 {download}`freqanal.py` 与 {download}`deriv_numerical.py` 中。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a2dbc955",
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib notebook\n",
    "\n",
    "from freqanal import FreqAnal\n",
    "from deriv_numerical import NumericDiff, NucCoordDerivGenerator\n",
    "\n",
    "import itertools\n",
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "from opt_einsum import contract as einsum\n",
    "from pyscf import gto, scf, hessian, lib, data\n",
    "\n",
    "np.set_printoptions(6, linewidth=150, suppress=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8290ec4",
   "metadata": {},
   "source": [
    "我们也需要进行单位换算。这在先前的若干文档中已经有所使用。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "94ee144f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.constants import physical_constants\n",
    "# https://docs.scipy.org/doc/scipy/reference/constants.html\n",
    "E_h = physical_constants[\"Hartree energy\"][0]\n",
    "a_0 = physical_constants[\"Bohr radius\"][0]\n",
    "N_A = physical_constants[\"Avogadro constant\"][0]\n",
    "c_0 = physical_constants[\"speed of light in vacuum\"][0]\n",
    "e_c = physical_constants[\"elementary charge\"][0]\n",
    "e_0 = physical_constants[\"electric constant\"][0]\n",
    "F = physical_constants[\"Faraday constant\"][0]\n",
    "k_B = physical_constants[\"Boltzmann constant\"][0]\n",
    "R = physical_constants[\"molar gas constant\"][0]\n",
    "h = physical_constants[\"Planck constant\"][0]\n",
    "hbar = physical_constants[\"reduced Planck constant\"][0]\n",
    "amu = physical_constants[\"atomic mass constant\"][0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8f1d201",
   "metadata": {},
   "source": [
    "除了文末的红外光谱绘制，我们使用的分子是不具有对称性的氨分子，基组 STO-3G。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "52cc252a",
   "metadata": {},
   "outputs": [],
   "source": [
    "mol = gto.Mole(atom=\"\"\"\n",
    "N  0.000000    0.000000    0.000000\n",
    "H  0.000000    0.000000    0.940000\n",
    "H  1.006874    0.000000   -0.260395\n",
    "H -1.037114   -0.277894   -0.640054\n",
    "\"\"\", basis=\"STO-3G\", verbose=0).build()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed25144d",
   "metadata": {},
   "source": [
    "## 数值三阶与四阶核坐标导数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "477e43ae",
   "metadata": {},
   "source": [
    "### 二阶导数回顾与频率数值"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "231f9cc5",
   "metadata": {},
   "source": [
    ":::{admonition} 记号定义\n",
    "\n",
    "**角标定义**\n",
    "\n",
    "- $A, B$：原子核标号；\n",
    "- $\\alpha, \\beta, \\gamma$：三维坐标的取向 (即可以取 $x, y, z$，也可能取转动惯量主轴，本文档多数时间选择后者)；\n",
    "- $i, j, k$：简振模式的编号。\n",
    "\n",
    "**物理量定义**\n",
    "\n",
    "- $A_\\alpha$：原子核 $A$ 的坐标三维分量 $\\alpha$；\n",
    "- $Q_i$：一单位的简振模式 $i$；\n",
    "- $Q_{A_\\alpha, i}$：简振模式转换矩阵，即 $i$ 在原子坐标分量 $A_\\alpha$ 的分量值。\n",
    "\n",
    "需要注意到，这些记号的定义与量化程序中的定义，也与之前文档的定义是冲突或不同的。读者需要注意记号的差别。\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b51c2285",
   "metadata": {},
   "source": [
    "我们知道，Hessian 矩阵是频率分析的必要矩阵，它即是二阶核坐标导数，及\n",
    "\n",
    "$$\n",
    "\\Phi_{A_\\alpha B_\\beta} = \\frac{\\partial^2 E}{\\partial A_t \\partial B_s}\n",
    "$$\n",
    "\n",
    "在原子坐标分量表示下，这应当是一个 $(A_\\alpha, B_\\beta): (3 n_\\mathrm{atm}, 3 n_\\mathrm{atm})$ 的矩阵。尽管依据程序不同，也可能是张量——在 PySCF 中，Hessian 的默认输出是 $(A, B, \\alpha, \\beta): (n_\\mathrm{atm}, n_\\mathrm{atm}, 3, 3)$ 维度的张量，但张量的大小与 $(A_\\alpha, B_\\beta)$ 实际上一致，经过转置两者就能相同。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5728540b",
   "metadata": {},
   "outputs": [],
   "source": [
    "natm = mol.natm\n",
    "nhess = natm * 3\n",
    "\n",
    "mf = scf.RHF(mol).run()\n",
    "mf_hess = mf.Hessian().run()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fad4ab80",
   "metadata": {},
   "source": [
    "我们也需要定义频率分析的实例 `fa`，其变量名是 `FreqAnal` 的首字母，与♂fa 乐器♂无关。下面的 code cell 输出的是以 $\\mathrm{cm^{-1}}$ 为简振振动频率 $\\omega_i$。\n",
    "\n",
    "如果要与 Gaussian 的结果有更好的印证，原子质量需要取与 Gaussian 相同的值，而不太适合用整数值。因此，这里没有用 PySCF 自带的 `mol.atom_mass_list`，而是使用一个函数 `get_atom_mass_list` 来解决问题。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b9427fd4",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_atom_mass_list(mol):\n",
    "    d = {1: 1.00782504, 6: 12., 7: 14.0030740, 8: 15.9949146}\n",
    "    return np.array([d[m] for m in mol.atom_charges()])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b4fd98e1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-969.746082, 1680.3876  , 1931.786797, 2059.643873, 3874.822068, 5095.777567])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fa = FreqAnal()\n",
    "fa.mol_weights = get_atom_mass_list(mol)\n",
    "fa.mol_coords = mol.atom_coords()\n",
    "fa.natm = mol.natm\n",
    "fa.mol_hess = mf_hess.de.swapaxes(1, 2)\n",
    "nvib = fa.freq.size\n",
    "fa.freq"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31c1492f",
   "metadata": {},
   "source": [
    ":::{admonition} 记号定义\n",
    "\n",
    "我们之后会经常作单位换算与量纲分析，因此这里尽量将目前与将来需要的物理量与量纲列出：\n",
    "\n",
    "- $Q_i$ 简振模式，单位 $\\mathrm{Bohr \\ amu^{1/2}}$；\n",
    "- $Q_{A_\\alpha i}$ 简振模量到分子坐标表象的转换矩阵，单位 $\\mathrm{amu^{-1/2}}$，程序调用 `fa.q`；\n",
    "- $Q_{A_\\alpha i}^\\mathrm{norm}$ 归一化的简振模量转换矩阵，无量纲，程序调用 `fa.qnorm`；\n",
    "- $\\omega_i$ 简振振动频率，单位 $\\mathrm{cm^{-1}}$，程序调用 `fa.freq`；\n",
    "- $\\nu_i$ 非谐振动频率，单位 $\\mathrm{cm^{-1}}$；\n",
    "- $\\lambda_i$ 二阶力常数，单位 $\\mathrm{\\mathit{E}_h \\ Bohr^{-2} \\ amu^{-1}}$；\n",
    "- $\\Phi_{A_\\alpha B_\\beta}$ 坐标表示的 Hessian 矩阵，单位 $\\mathrm{\\mathit{E}_h \\ Bohr^{-2}}$；\n",
    "- $\\Phi_{ij}$ 简振表示的 Hessian 矩阵，单位 $\\mathrm{\\mathit{E}_h \\ Bohr^{-2} \\ amu^{-1}}$；\n",
    "- $\\Phi_{ijk}$ 简振表示的三阶导数，单位 $\\mathrm{\\mathit{E}_h \\ Bohr^{-3} \\ amu^{-3/2}}$；\n",
    "- $\\Phi_{ijkl}$ 简振表示的四阶导数，单位 $\\mathrm{\\mathit{E}_h \\ Bohr^{-4} \\ amu^{-2}}$；\n",
    "- $I_\\alpha$ 转动惯量，单位 $\\mathrm{amu \\ Bohr^{2}}$；\n",
    "- $\\varpi_\\alpha$ 转动常数，单位 $\\mathrm{cm^{-1}}$；\n",
    "- $\\zeta_{ij}^\\alpha$ Coriolis 耦合常数，无量纲；\n",
    "- $\\theta_i (T)$ 温度矫正系数，无量纲；\n",
    "- $\\boldsymbol{\\mu}$ 偶极矩，单位 $\\mathrm{Debye}$；\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "214efd00",
   "metadata": {},
   "source": [
    "为了后文的便利，我们也会经常使用在简振模式表示下的 Hessian 矩阵：\n",
    "\n",
    "$$\n",
    "\\Phi_{ij} = \\frac{\\partial^2 E}{\\partial Q_i \\partial Q_j}\n",
    "$$\n",
    "\n",
    "从定义上，简振模式是分子振动的 Hessian 矩阵的本征模式，因此 $\\Phi_{ij}$ 实际上是对角矩阵 $\\lambda_i \\delta_{ij}$。其中，$\\lambda_i$ 是简振模式 $i$ 的振动强度。坐标表示与简振表示的换算关系是\n",
    "\n",
    "$$\n",
    "\\Phi_{ij} = \\sum_{A_\\alpha B_\\beta} Q_{A_\\alpha i} \\Phi_{A_\\alpha B_\\beta} Q_{B_\\beta j}\n",
    "$$\n",
    "\n",
    "我们用 `deriv_2` 表示 $\\Phi_{ij}$。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "7be4a977",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.035588, -0.      ,  0.      ,  0.      , -0.      , -0.      ],\n",
       "       [-0.      ,  0.106859,  0.      , -0.      ,  0.      ,  0.      ],\n",
       "       [ 0.      ,  0.      ,  0.141224, -0.      ,  0.      ,  0.      ],\n",
       "       [ 0.      , -0.      , -0.      ,  0.160537, -0.      , -0.      ],\n",
       "       [ 0.      ,  0.      , -0.      , -0.      ,  0.568192, -0.      ],\n",
       "       [-0.      , -0.      , -0.      , -0.      , -0.      ,  0.982681]])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "deriv_2 = einsum(\"Pi, PQ, Qj -> ij\", fa.q, fa.mol_hess.reshape(nhess, nhess), fa.q)\n",
    "deriv_2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3f2c342",
   "metadata": {},
   "source": [
    "我们注意到这是一个对称矩阵。实际上，简振模式从定义上就是在 Hessian 矩阵去除了平动、转动贡献之后的本征振动模式；因此，在简振模式表示下的 Hessian 矩阵自然应当是对角化的。其对角元我们之后也经常用到，因此以 `lambd` $\\lambda_i = \\Phi_{ij} \\delta_{ij}$ 表示，物理量上称为力常数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3052659c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-0.035588,  0.106859,  0.141224,  0.160537,  0.568192,  0.982681])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lambd = deriv_2.diagonal()\n",
    "lambd"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42b4bfee",
   "metadata": {},
   "source": [
    "力常数 $\\lambda_i$ 它与频率 $\\omega_i$ 之间的关系是\n",
    "\n",
    "$$\n",
    "\\omega_i = \\frac{\\sqrt{\\lambda_i}}{2 \\pi c_0} = \\frac{1}{2 \\pi c_0} \\sqrt{\\frac{k_i}{m}}, \\quad \\lambda = (2 \\pi c_0 \\omega_i)^2\n",
    "$$\n",
    "\n",
    "它与我们经常看到的另一个力常数 $k_i$ 不同。从量纲上，$\\lambda_i$ 是 $\\mathrm{[T]^{-2}}$。如果考虑到一些比较麻烦的单位换算，我们可以通过频率 $\\omega_i$ 给出力常数 $\\lambda_i$。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f72424d",
   "metadata": {},
   "source": [
    "单位换算的原则如下。我们发现，对于等式左边的待求量完全是原子单位，但右边则完全是经过变动的 SI 单位制 (波数以 $\\mathrm{cm^{-1}}$ 而非以 $\\mathrm{m^{-1}}$ 表示)。我们以 SI 单位制作为中间单位，\n",
    "- 对等式左边，$\\lambda_i$ 的单位是 $\\mathrm{\\mathit{E}_h \\ Bohr^{-2} \\ amu^{-1}}$，我们要对应地除以这部分单位的 SI 转换；\n",
    "- 对等式右边，$\\omega_i$ 的单位是 $\\mathrm{cm^{-1}}$，我们要乘以这部分的 SI 转换 ($100$)。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "e8ea6546",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.035588, 0.106859, 0.141224, 0.160537, 0.568192, 0.982681])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(\n",
    "    (2 * np.pi * c_0 * fa.freq)**2        # equation\n",
    "    / (E_h * a_0**-2 * amu**-1) * 100**2  # unit conversion\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e305c0b",
   "metadata": {},
   "source": [
    "我们最后讨论一下简振模量矩阵 $Q_{A_\\alpha i}$ 与其归一化形式 $Q_{A_\\alpha i}^\\mathrm{norm}$ 之间的关系。在 Gaussian 的输出中，我们一般只会看到 $Q_{A_\\alpha i}^\\mathrm{norm}$，它具有下述限制：\n",
    "\n",
    "$$\n",
    "\\sum_{A_\\alpha} (Q_{A_\\alpha i}^\\mathrm{norm})^2 = 1 , \\ \\forall i\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3be695fe",
   "metadata": {},
   "source": [
    "正因为这种归一化条件，$Q_{A_\\alpha i}^\\mathrm{norm}$ 实际上是没有量纲的。但我们以后一直要遇到与处理的简振模量，是所谓分子质量折合过的模量，其量纲是 $\\mathrm{[M]^{-1/2}}$。它也可以从归一化的简振模量导出，其中 $m_\\mathrm{A}$ 是 $A$ 原子的质量：\n",
    "\n",
    "$$\n",
    "Q_{A_\\alpha i} = Q_{A_\\alpha i}^\\mathrm{norm} \\left( \\sum_{A_\\alpha} \\big( Q_{A_\\alpha i}^\\mathrm{norm} \\sqrt{m_\\mathrm{A}} \\big)^2 \\right)^{-1/2}\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "868a61c2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.allclose(fa.qnorm / np.linalg.norm(fa.qnorm * np.sqrt(np.repeat(get_atom_mass_list(mol), 3))[:, None], axis=0), fa.q)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a520b3cb",
   "metadata": {},
   "source": [
    "### 数值三阶导数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ab7f7e8",
   "metadata": {},
   "source": [
    "我们以后一直会使用简振坐标表示下的能量导数；并且我们注意到简振模式的数量是 $3N-6$，比原子坐标分量的 $3N$ 数量要少一些。因此，在求取数值导数时，我们会希望使用简振模式作为实际被求导量。\n",
    "\n",
    "我们需要的三阶导数量是\n",
    "\n",
    "$$\n",
    "\\Phi_{ijk} = \\frac{\\partial^3 E}{\\partial Q_i \\partial Q_j \\partial Q_k}\n",
    "$$\n",
    "\n",
    "但在求取数值导数时，我们可以选择一个量作为数值偏移量，譬如 $Q_k$；而剩下的量则是解析地计算。但我们也注意到，程序上默认给出的是原子坐标表示的 $\\Phi_{A_\\alpha B_\\beta}$，还需要我们作转换得到 $\\Phi_{ij}$。因此，数值导数的求取方法是\n",
    "\n",
    "$$\n",
    "\\Phi_{ijk} = \\sum_{A_\\alpha B_\\beta} Q_{A_\\alpha i} Q_{B_\\beta j} \\Phi_{A_\\alpha B_\\beta k} = \\sum_{A_\\alpha B_\\beta} Q_{A_\\alpha i} Q_{B_\\beta j} \\frac{\\Phi_{A_\\alpha B_\\beta} (\\delta Q_k) - \\Phi_{A_\\alpha B_\\beta} (-\\delta Q_k)}{2 \\delta Q_k} \n",
    "$$\n",
    "\n",
    "下面的程序就是以 $0.01 \\ \\mathrm{\\mathring{A}} \\ \\mathrm{amu}^{1/2}$ 为偏移大小，求取对简振坐标导数的程序："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "91ded136",
   "metadata": {},
   "outputs": [],
   "source": [
    "class ModeDerivGenerator(NucCoordDerivGenerator):\n",
    "\n",
    "    def __init__(self, mol, mf_func, q, interval=3e-3):\n",
    "        self.q = q\n",
    "        super(ModeDerivGenerator, self).__init__(mol, mf_func, stencil=3, interval=interval)\n",
    "    \n",
    "    def init_objects(self):\n",
    "        nmode = self.q.shape[1]\n",
    "        self.objects = np.empty((nmode, 2), dtype=object)\n",
    "    \n",
    "    def perform_mf(self):\n",
    "        natm = self.mol.natm\n",
    "        nmode = self.q.shape[1]\n",
    "        for nq, norm in enumerate(self.q.T):\n",
    "            norm = norm.reshape(natm, 3)\n",
    "            movelist = [(A, t, norm[A, t]) for A in range(natm) for t in range(3)]\n",
    "            self.objects[nq, 1] = self.mf_func(self.move_mol(movelist))\n",
    "            movelist = [(A, t, - norm[A, t]) for A in range(natm) for t in range(3)]\n",
    "            self.objects[nq, 0] = self.mf_func(self.move_mol(movelist))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "997597f2",
   "metadata": {},
   "source": [
    "我们将 Hessian 对简振坐标的导数实例定为 `num_hess`："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "3db7bc7d",
   "metadata": {},
   "outputs": [],
   "source": [
    "num_hess = ModeDerivGenerator(mol, lambda mol: scf.RHF(mol).run().Hessian().run(), fa.q, interval=0.01)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ce5b066",
   "metadata": {},
   "source": [
    "使用 `NumericDiff` 直接求导的结果是 $\\Phi_{A_\\alpha B_\\beta k}$。我们需要再对其进行转换再得到 $\\Phi_{ijk}$ `deriv_3`："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "7ad857d5",
   "metadata": {},
   "outputs": [],
   "source": [
    "tmp_3 = NumericDiff(num_hess, lambda mf: mf.de.swapaxes(1, 2).reshape(nhess, nhess)).derivative\n",
    "deriv_3 = einsum(\"Ai, Bj, kAB -> ijk\", fa.q, fa.q, tmp_3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7168979e",
   "metadata": {},
   "source": [
    "严格地来说，$\\Phi_{ijk}$ 应当是具有六重对称性的张量。因此，我们还可以对其进行对称化，使得结果定性上更正确："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "91f4a16d",
   "metadata": {},
   "outputs": [],
   "source": [
    "deriv_3 = 1/3 * (deriv_3 + deriv_3.transpose(1, 2, 0) + deriv_3.transpose(2, 0, 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f3c2530",
   "metadata": {},
   "source": [
    "### 数值四阶导数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39cbf24e",
   "metadata": {},
   "source": [
    "我们通过三点差分的方法，给出了三阶导数。尽管我们无法求出全部的四阶导数，但利用刚才求取三阶导数的数据，我们可以求取 $\\Phi_{ijkk}$ 形式的四阶导数：\n",
    "\n",
    "$$\n",
    "\\Phi_{ijkk} = \\frac{\\partial^2}{\\partial Q_k^2} \\frac{\\partial^2 E}{\\partial Q_i \\partial Q_j} = \\frac{\\Phi_{ij} (\\delta Q_k) - 2 \\Phi_{ij} (0) + \\Phi_{ij} (-\\delta Q_k)}{(\\delta Q_k)^2}\n",
    "$$\n",
    "\n",
    "注意到利用现有的数据，我们只能求取 $\\Phi_{ijkk}$，而不能求取更一般的 $\\Phi_{ijkl}$。该张量也具有对称性；我们可以对 $i, j$ 角标进行对称化。我们将会用 `deriv_4` 表示 $\\Phi_{ijkk}$，维度是 $(i, j, k)$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "99354a7c",
   "metadata": {},
   "outputs": [],
   "source": [
    "hess_gathered = np.array([[mf.de.swapaxes(1, 2).reshape(nhess, nhess) for mf in l] for l in num_hess.objects])\n",
    "tmp_4 = einsum(\"ksAB, Ai, Bj -> skij\", hess_gathered, fa.q, fa.q)\n",
    "deriv_4 = (tmp_4[0] + tmp_4[1] - 2 * deriv_2) / (num_hess.interval**2)  # finite diff\n",
    "deriv_4 = (deriv_4 + deriv_4.swapaxes(-1, -2)) / 2                      # symmetrize\n",
    "deriv_4 = einsum(\"kij -> ijk\", deriv_4)                                 # subscript transform"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f427af03",
   "metadata": {},
   "source": [
    "## 非谐频率矫正"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46084b6f",
   "metadata": {},
   "source": [
    "在求取频率矫正前，我们需要先获得矩阵 $\\xi_{ij}$ `xmat`。该矩阵与频率相同单位，即 $\\mathrm{cm}^{-1}$。这里的公式主要参考 Barone eq. (36-38)，但在与一些系数有关的问题上不太相同。该矩阵对非谐矫正后的频率至关重要。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3460b1b0",
   "metadata": {},
   "source": [
    "### 四阶导数对 $\\xi_{ij}$ 的贡献"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b72cf91",
   "metadata": {},
   "source": [
    "若除开单位换算，四阶导数对矩阵 $\\xi_{ij}$ 的贡献是\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "\\xi_{ii} &\\leftarrow \\frac{\\hbar}{2 \\pi c_0} \\frac{1}{16 \\lambda_i} \\Phi_{iiii} \\\\\n",
    "\\xi_{ij} &\\leftarrow \\frac{\\hbar}{2 \\pi c_0} \\frac{1}{4 \\sqrt{|\\lambda_i \\lambda_j|}} \\Phi_{iijj} \\quad (i \\neq j)\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "之所以表达式中需要引入绝对值，是因为我们同时处理实频与虚频。虚频下，$\\lambda_i$ 小于零，无法开根号。依据 Miller, et al. [^Miller.CPL.1990] 的表达式，实际上对于有且仅有一个虚频的 $Q_i$，其对应的 $\\xi_{ij}$ 也应当是虚数。当前的分子也恰好是有且仅有一个虚频，并且实际上虚数的 $\\xi_{ij}$ 可以与虚数的 $\\omega_i$ 相加得到非谐频率 $\\nu_i$；因此就这种过渡态情形，在程序实现上，可以对虚频与实频一视同仁。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "5bced766",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ -59.929105,   17.359227,    2.022484,  -26.747814,  -89.778445, -133.911891],\n",
       "       [  17.360842,   11.4939  ,   18.955104,   -6.407765,   -6.83072 , -112.008037],\n",
       "       [   2.024055,   18.952477,    4.4002  ,   42.205352,  -50.906768,  -38.849444],\n",
       "       [ -26.737152,   -6.40661 ,   42.197109,   45.874797,  -16.574222,   -5.321896],\n",
       "       [ -89.725547,   -6.828563,  -50.876096,  -16.565645,   62.64625 ,    1.480829],\n",
       "       [-133.825551, -111.932215,  -38.826908,   -5.319965,    1.480938,   70.703952]])"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xmat_4 = np.zeros((nvib, nvib))\n",
    "for i in range(nvib):\n",
    "    xmat_4[i, i] = deriv_4[i,i,i] / (16 * lambd[i])\n",
    "    for j in range(nvib):\n",
    "        if i == j: continue\n",
    "        xmat_4[i, j] = deriv_4[i,i,j] / (4 * np.sqrt(np.abs(lambd[i] * lambd[j])))\n",
    "xmat_4 *= (hbar / (2 * np.pi * c_0)) * (a_0**-2 * amu**-1) / (100)\n",
    "xmat_4"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "067d3512",
   "metadata": {},
   "source": [
    "### 三阶导数对 $\\xi_{ij}$ 的贡献"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ac01e6a",
   "metadata": {},
   "source": [
    "三阶导数对 $\\xi_{ij}$ 的贡献核算相对复杂。我们首先处理对角线的贡献：\n",
    "\n",
    "$$\n",
    "\\xi_{ii} \\leftarrow - \\frac{\\hbar}{2 \\pi c_0} \\frac{1}{16 \\lambda_i} \\left( \\frac{5}{3 \\lambda_i} \\Phi_{iii}^2 + \\frac{8 \\lambda_i - 3 \\lambda_j}{\\lambda_j (4 \\lambda_i - \\lambda_j)} \\Phi_{iij}^2 \\right)\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "81315833",
   "metadata": {},
   "outputs": [],
   "source": [
    "xmat_3 = np.zeros((nvib, nvib))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "9e51f0e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(nvib):\n",
    "    xmat_3[i, i] -= deriv_3[i,i,i]**2 * 5 / (3 * lambd[i])\n",
    "    for j in range(nvib):\n",
    "        if i == j: continue\n",
    "        xmat_3[i, i] -= deriv_3[i,i,j]**2 * (8 * lambd[i] - 3 * lambd[j]) / (lambd[j] * (4 * lambd[i] - lambd[j]))\n",
    "    xmat_3[i, i] /= 16 * lambd[i]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c8924660",
   "metadata": {},
   "source": [
    "随后处理非对角线的贡献 ($i \\neq j$)：\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "\\xi_{ij} &\\leftarrow - \\frac{\\hbar}{2 \\pi c_0} \\frac{1}{4 \\sqrt{|\\lambda_i \\lambda_j|}} \\left( \\frac{2}{4 \\lambda_i - \\lambda_j} \\Phi_{iij}^2 + \\frac{2}{4 \\lambda_j - \\lambda_i} \\Phi_{ijj}^2 + \\frac{\\Phi_{iii} \\Phi_{ijj}}{\\lambda_i} + \\frac{\\Phi_{jjj} \\Phi_{iij}}{\\lambda_j} \\right) \\\\\n",
    "&\\quad + \\frac{\\hbar}{2 \\pi c_0} \\frac{1}{4 \\sqrt{|\\lambda_i \\lambda_j|}} \\sum_{k \\notin \\{i, j\\}} \\left[ \\frac{2 (\\lambda_i + \\lambda_j - \\lambda_k)}{\\Delta_{ijk}} \\Phi_{ijk}^2 - \\frac{\\Phi_{iik} \\Phi_{jjk}}{\\lambda_k} \\right]\n",
    "\\end{align}\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "32515fcd",
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(nvib):\n",
    "    for j in range(nvib):\n",
    "        if i == j: continue\n",
    "        xmat_3[i, j] -= deriv_3[i,i,j]**2 * 2 / (4 * lambd[i] - lambd[j])\n",
    "        xmat_3[i, j] -= deriv_3[i,j,j]**2 * 2 / (4 * lambd[j] - lambd[i])\n",
    "        xmat_3[i, j] -= deriv_3[i,i,i] * deriv_3[i,j,j] / lambd[i]\n",
    "        xmat_3[i, j] -= deriv_3[j,j,j] * deriv_3[i,i,j] / lambd[j]\n",
    "        for k in range(nvib):\n",
    "            if len(set([i, j, k])) != 3: continue\n",
    "            delta_ijk = lambd[i]**2 + lambd[j]**2 + lambd[k]**2 - 2 * (lambd[i]*lambd[j] + lambd[j]*lambd[k] + lambd[k]*lambd[i])\n",
    "            xmat_3[i, j] += deriv_3[i,j,k]**2 * 2 * (lambd[i] + lambd[j] - lambd[k]) / delta_ijk\n",
    "            xmat_3[i, j] -= deriv_3[i,i,k] * deriv_3[j,j,k] / lambd[k]\n",
    "        xmat_3[i, j] /= 4 * np.sqrt(np.abs(lambd[i] * lambd[j]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "20540b58",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[   6.436059,  -17.659895,  -12.843587,  -17.730696,   49.859864,   86.717056],\n",
       "       [ -17.659895,  -18.294258,  -35.959998,  -46.395273,    2.625465,   94.139235],\n",
       "       [ -12.843587,  -35.959998,  -65.430162, -108.220206,  228.295265,   26.274758],\n",
       "       [ -17.730696,  -46.395273, -108.220206, -115.728507,  -19.13443 ,   -3.494852],\n",
       "       [  49.859864,    2.625465,  228.295265,  -19.13443 , -111.055075,  -10.265471],\n",
       "       [  86.717056,   94.139235,   26.274758,   -3.494852,  -10.265471, -112.711441]])"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xmat_3 *= (hbar / (2 * np.pi * c_0)) * (a_0**-2 * amu**-1) / (100)\n",
    "xmat_3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2f91e7e",
   "metadata": {},
   "source": [
    "### Coriolis 矫正对 $\\xi_{ij}$ 的贡献"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "66ec8101",
   "metadata": {},
   "source": [
    "Coriolis 矫正的贡献方式是 (允许 $i = j$)\n",
    "\n",
    "$$\n",
    "\\xi_{ij} \\leftarrow \\sum_\\alpha \\frac{\\lambda_i + \\lambda_j}{\\sqrt{|\\lambda_i \\lambda_j|}} \\varpi_\\alpha (\\zeta_{ij}^\\alpha)^2\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4174f2c7",
   "metadata": {},
   "source": [
    "这里引入了一些特殊的记号。被求和的角标 $\\alpha$ 尽管是 $x, y, z$ 三个取向之一，但在求取 Coriolis 矫正贡献时，它必须是转动惯量主轴。\n",
    "\n",
    "我们在通过 Hessian 矩阵得到分子振动频率时，需要去除转动的三个自由度贡献。那时我们已经计算过与转动有关的各种中间变量。$\\varpi_\\alpha$ `rot_wavenum` 是以 $\\mathrm{cm^{-1}}$ 为单位的转动常数：\n",
    "\n",
    "$$\n",
    "\\varpi_\\alpha = \\frac{h}{8 \\pi^2 c_0 I_\\alpha}\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "54332c49",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([13.875725,  7.153573,  4.775983])"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rot_wavenum = h / (8 * np.pi**2 * c_0 * fa.rot_eig) * (a_0**-2 * amu**-1) / (100)\n",
    "rot_wavenum"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a27a729",
   "metadata": {},
   "source": [
    "而 $\\zeta_{ij}^\\alpha$ `zeta` Coriolis 耦合常数通过下式进行计算 (Barone, eq (11)，维度 $(\\alpha, i, j)$，无量纲)：\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "\\zeta_{ij}^\\alpha &= \\sum_k (L_{A_\\beta i} L_{A_\\gamma j} - L_{A_\\gamma i} L_{A_\\beta j}) \\\\\n",
    "L_{A_\\alpha i} &= \\sum_\\beta Q_{A_\\beta i} R_{\\beta \\alpha} \\sqrt{m_A}\n",
    "\\end{align}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ed28d47",
   "metadata": {},
   "source": [
    "其中，$R_{\\beta \\alpha}$ 转动的本征向量，无量纲。其本征值是转动惯量，这在 [频率分析 (1)](freq_1.ipynb) 中有所提及。同时，求取 $\\zeta_{ij}^\\alpha$ 时，其表达式的分量 $\\alpha, \\beta, \\gamma$ 必须按照右手坐标系排序。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "c3d10d01",
   "metadata": {},
   "outputs": [],
   "source": [
    "q_ = einsum(\"Aβi, βα, A -> Aαi\", fa.q.reshape(natm, 3, nvib), fa.rot_vec, np.sqrt(get_atom_mass_list(mol)))\n",
    "zeta_x = einsum(\"Ai, Aj -> ij\", q_[:, 1, :], q_[:, 2, :]) - einsum(\"Ai, Aj -> ij\", q_[:, 2, :], q_[:, 1, :])\n",
    "zeta_y = einsum(\"Ai, Aj -> ij\", q_[:, 2, :], q_[:, 0, :]) - einsum(\"Ai, Aj -> ij\", q_[:, 0, :], q_[:, 2, :])\n",
    "zeta_z = einsum(\"Ai, Aj -> ij\", q_[:, 0, :], q_[:, 1, :]) - einsum(\"Ai, Aj -> ij\", q_[:, 1, :], q_[:, 0, :])\n",
    "zeta = np.array([zeta_x, zeta_y, zeta_z])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d2519df",
   "metadata": {},
   "source": [
    "同时，转动本征向量还可以用来将分子旋转到转动主轴坐标系，且该坐标系的 $I_x < I_y < I_z$。该坐标系在 Gaussian 中称为 Eckart Orientation。我们可以输出该坐标系下以 Angstrom 为单位的分子构型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "1b52ceca",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.003095, -0.002241, -0.016268],\n",
       "       [ 0.384988,  0.851931,  0.073996],\n",
       "       [ 0.805212, -0.657419,  0.078348],\n",
       "       [-1.233207, -0.163374,  0.07369 ]])"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fa.centered_coord @ fa.rot_vec * a_0 * 1e10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0df9a2c0",
   "metadata": {},
   "source": [
    "至此，我们就可以将 Coriolis 矫正的贡献计算出来。\n",
    "\n",
    "$$\n",
    "\\xi_{ij} \\leftarrow \\sum_\\alpha \\frac{\\lambda_i + \\lambda_j}{\\sqrt{|\\lambda_i \\lambda_j|}} \\varpi_\\alpha (\\zeta_{ij}^\\alpha)^2\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "ac21f6d9",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.      ,  6.485503,  2.854787,  7.462297, 14.215879, 25.469408],\n",
       "       [ 6.485503,  0.      ,  0.862218,  2.938909,  0.906227,  8.749904],\n",
       "       [ 2.854787,  0.862218,  0.      ,  0.883756,  5.835533,  3.491808],\n",
       "       [ 7.462297,  2.938909,  0.883756,  0.      ,  1.970819,  0.474133],\n",
       "       [14.215879,  0.906227,  5.835533,  1.970819,  0.      ,  0.009302],\n",
       "       [25.469408,  8.749904,  3.491808,  0.474133,  0.009302,  0.      ]])"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xmat_coriol = np.zeros((nvib, nvib))\n",
    "for i in range(nvib):\n",
    "    for j in range(nvib):\n",
    "        for ixyz in range(3):\n",
    "            xmat_coriol[i, j] += zeta[ixyz, i, j]**2 * rot_wavenum[ixyz]\n",
    "        xmat_coriol[i, j] *= (lambd[i] + lambd[j]) / np.sqrt(np.abs(lambd[i] * lambd[j]))\n",
    "xmat_coriol"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee4bbe5a",
   "metadata": {},
   "source": [
    ":::{danger}\n",
    "\n",
    "对于 Gaussian 09 rev. D01 及 C01，其输出的 Coriolis 贡献是错误的。其原因在于没有将分子坐标预先转置到 Eckart Orientation 下，而仍然在输入坐标下进行计算。将这种坐标与转动惯量主轴的转动频率作乘积没有意义。也因此，该版本的 Gaussian 实际上无法正确地输出频率的矫正；除非输入坐标与 Eckart Orientation 一致。\n",
    "\n",
    "如果要重复该版本的结果，**对于当前的分子**，可以使用后面一个被折叠的 code cell 代码。\n",
    "\n",
    "我们之前号称正确的实现方式，与 Gaussian 16 rev. B01 的结果应当一致。\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "f4f06ea1",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.      ,  4.90998 ,  3.505416,  9.864751, 10.909095, 26.892735],\n",
       "       [ 4.90998 ,  0.      ,  0.933722,  3.050355,  0.933074,  9.206211],\n",
       "       [ 3.505416,  0.933722,  0.      ,  0.902214,  5.887021,  3.409958],\n",
       "       [ 9.864751,  3.050355,  0.902214,  0.      ,  1.987215,  0.43257 ],\n",
       "       [10.909095,  0.933074,  5.887021,  1.987215,  0.      ,  0.009969],\n",
       "       [26.892735,  9.206211,  3.409958,  0.43257 ,  0.009969,  0.      ]])"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def xmat_coriol_G09():\n",
    "    # -- What makes different --\n",
    "    q_ = einsum(\"Aαi, A -> Aαi\", fa.q.reshape(natm, 3, nvib), np.sqrt(get_atom_mass_list(mol)))\n",
    "    rot_in_G09 = rot_wavenum[0], rot_wavenum[2], rot_wavenum[1]\n",
    "    # -- The rest are merely the same --\n",
    "    zeta = np.zeros((3, nvib, nvib))\n",
    "    for α, β, γ in [(0, 1, 2), (1, 2, 0), (2, 0, 1)]:\n",
    "        zeta[α] = einsum(\"Ai, Aj -> ij\", q_[:, β, :], q_[:, γ, :]) - einsum(\"Ai, Aj -> ij\", q_[:, γ, :], q_[:, β, :])\n",
    "    xmat_coriol = einsum(\"αij, α, ij -> ij\", zeta**2, rot_in_G09, (lambd[:, None] + lambd[None, :]) / np.sqrt(np.abs(lambd[:, None] * lambd[None, :])))\n",
    "    return xmat_coriol\n",
    "xmat_coriol_G09()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "ab2893b3",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Coriolis contributions to Xmat \r\n",
      "                1             2             3             4             5 \r\n",
      "      1  0.000000D+00\r\n",
      "      2  0.268927D+02  0.000000D+00\r\n",
      "      3  0.109091D+02  0.996906D-02  0.000000D+00\r\n",
      "      4  0.986475D+01  0.432572D+00  0.198722D+01  0.000000D+00\r\n",
      "      5  0.350541D+01  0.340996D+01  0.588702D+01  0.902213D+00  0.000000D+00\r\n",
      "      6  0.490997D+01  0.920621D+01  0.933076D+00  0.305035D+01  0.933724D+00\r\n",
      "                6 \r\n",
      "      6  0.000000D+00\r\n"
     ]
    }
   ],
   "source": [
    "! head -n 9725 anharm-G09C01.log | tail -n 10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98825016",
   "metadata": {},
   "source": [
    "### 总 $\\xi_{ij}$ 矩阵与非谐频率的导出"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46fb5e42",
   "metadata": {},
   "source": [
    "我们首先将四阶导数、三阶导数、Coriolis 的贡献相加，得到总 $\\xi_{ij}$ 矩阵。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "a14acd7d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-53.493046,   6.184835,  -7.966316, -37.016213, -25.702702, -21.725427],\n",
       "       [  6.18645 ,  -6.800358, -16.142676, -49.864129,  -3.299028,  -9.118898],\n",
       "       [ -7.964745, -16.145302, -61.029962, -65.131098, 183.22403 ,  -9.082879],\n",
       "       [-37.005551, -49.862974, -65.139341, -69.85371 , -33.737833,  -8.342616],\n",
       "       [-25.649804,  -3.296871, 183.254702, -33.729256, -48.408825,  -8.77534 ],\n",
       "       [-21.639087,  -9.043076,  -9.060343,  -8.340685,  -8.775231, -42.007489]])"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xmat = xmat_4 + xmat_3 + xmat_coriol\n",
    "xmat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e3491ff",
   "metadata": {},
   "source": [
    "这可以与 Gaussian 的输出作比对。需要注意，**我们的结果与 Gaussian 并不完全一致**，且不仅是由于简振模式的排序不同所产生。这是由于 Fermi 共振所致，我们后面会提及。**我们的程序无法处理 Fermi 共振**，但 Gaussian 会有一些办法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "5c425681",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Total Anharmonic X Matrix (in cm^-1)\r\n",
      " ------------------------------------\r\n",
      "                1             2             3             4             5\r\n",
      "      1 -0.534804D+02\r\n",
      "      2 -0.216582D+02 -0.420071D+02\r\n",
      "      3 -0.256619D+02 -0.877403D+01 -0.484077D+02\r\n",
      "      4 -0.370099D+02 -0.834034D+01 -0.337307D+02 -0.698507D+02\r\n",
      "      5 -0.797061D+01 -0.906609D+01 -0.296660D+02 -0.651376D+02 -0.780405D+01\r\n",
      "      6  0.617458D+01 -0.905380D+01 -0.329760D+01 -0.498632D+02 -0.161479D+02\r\n",
      "                6\r\n",
      "      6 -0.680891D+01\r\n"
     ]
    }
   ],
   "source": [
    "! head -n 14013 anharm-G16B01.log | tail -n 11"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "53fd4c20",
   "metadata": {},
   "source": [
    "依据 Barone eq. (43)，非谐频率很容易地通过下式给出 (单位 $\\mathrm{cm^{-1}}$)：\n",
    "\n",
    "$$\n",
    "\\nu_i = \\omega_i + 2 \\xi_{ii} + \\frac{1}{2} \\sum_{j \\neq i} \\xi_{ij} = \\omega_i + \\frac{3}{2} \\xi_{ii} + \\frac{1}{2} \\sum_j \\xi_{ij}\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "422e4a79",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-1119.845085,  1630.667744,  1852.176877,  1822.892296,  3833.906134,  4983.333379])"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fa.freq + 1.5 * xmat.diagonal() + 0.5 * xmat.sum(axis=-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "59493bc0",
   "metadata": {},
   "source": [
    "当我们与 Gaussian 的非谐频率进行比对时，会发现我们 $\\mathrm{3834 \\ cm^{-1}}$ 波数的结果与 Gaussian 的 $\\mathrm{3748 \\ cm^{-1}}$ 相差很大。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "b52cd071",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Fundamental Bands\r\n",
      " -----------------\r\n",
      "     Mode(n)      Status      E(harm)  E(anharm)     Aa(x)      Ba(y)      Ca(z)\r\n",
      "        1(1)      active      -969.747 -1119.771  14.263374   7.063101   4.568200\r\n",
      "        2(1)      active      5095.778  4983.317  14.043335   6.985596   4.575906\r\n",
      " H      3(1)      active      3874.822  3747.756  14.108724   6.929780   4.566570\r\n",
      "        4(1)      active      2059.644  1822.902  14.182793   6.771150   4.581152\r\n",
      "        5(1)      active      1931.787  1852.185  14.252150   7.053448   4.510857\r\n",
      "        6(1)      active      1680.388  1630.676  14.460822   7.057768   4.466441\r\n"
     ]
    }
   ],
   "source": [
    "! head -n 14193 anharm-G16B01.log | tail -n 9"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34aae2d8",
   "metadata": {},
   "source": [
    "这是源于 Gaussian 有对近简并倍频振动模式 (Fermi 共振) 的处理。在我们的问题中，$\\omega_4 - 2 \\omega_2 = 3834 - 2 \\times 1852 = 11 (\\mathrm{cm^{-1}})$ 被认为是倍频近简并的："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "ff983441",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "11.248473679877407"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fa.freq[4] - 2 * fa.freq[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "16c9b5b7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Fermi resonances\r\n",
      " ----------------\r\n",
      "\r\n",
      "     I      J  +   K   Freq. Diff.  Red. Cubic Const.  PT2-Variat.Diff.\r\n",
      "      3      5      5       11.248         138.473           1009.207\r\n"
     ]
    }
   ],
   "source": [
    "! head -n 13948 anharm-G16B01.log | tail -n 5"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68d2e3c0",
   "metadata": {},
   "source": [
    "它对下述三阶导数贡献项 $\\xi_{42} = \\xi_{24}$ 会有非常大的贡献 (注意到 $\\lambda_i \\propto \\omega_i^2$，因此下式中分母有 $\\omega_4 - 2 \\omega_2$ 的因式)：\n",
    "\n",
    "$$\n",
    "\\xi_{24} \\leftarrow - \\frac{\\hbar}{2 \\pi c_0} \\frac{1}{4 \\sqrt{|\\lambda_2 \\lambda_4|}} \\frac{2}{4 \\lambda_2 - \\lambda_4} \\Phi_{224}^2 \n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e2fd07a",
   "metadata": {},
   "source": [
    "这类表达式可以拆分为共振项与非共振项：\n",
    "\n",
    "$$\n",
    "\\frac{1}{4 \\lambda_i - \\lambda_j} = \\frac{1}{(2 \\pi c_0)^2} \\left( \\underset{\\text{non-resonant}}{\\frac{1}{4 \\omega_i (2 \\omega_i + \\omega_j)}} + \\underset{\\text{resonant}}{\\frac{1}{4 \\omega_i (2 \\omega_i - \\omega_j)}} \\right)\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffd8665d",
   "metadata": {},
   "source": [
    "在 Gaussian 中，当被判断为 Fermi 共振时，就会直接排除共振项，而只保留非共振项，以避免频率矫正的奇点。同时会在非谐频率输出的部分用记号 `H` 表示这种 Fermi 共振效应。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87fd4d8c",
   "metadata": {},
   "source": [
    "## 简振坐标平均偏移"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36471d33",
   "metadata": {},
   "source": [
    "为了计算分子的各种性质 (譬如偶极、红外等光谱性质) 的非谐矫正矫正，我们需要给出简振坐标的平均偏移量 $\\langle Q_i \\rangle$ 与二阶平均偏移量 $\\langle Q_i Q_j \\rangle$。\n",
    "\n",
    "我们在这一节中，为了与 Gaussian 的结果作比对，暂时不考虑转动矫正效应。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd6ea709",
   "metadata": {},
   "source": [
    "### 温度矫正效应"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "443c9603",
   "metadata": {},
   "source": [
    "我们现在要考虑温度对分子振动的影响。一般来说，温度越高，分子的振动会越剧烈，其各种谱学性质与 $0 \\ K$ 下的结果会偏差越大。这种温度效应是通过近似的配分函数所给出 (类似于 softmax 的效果)。虚频被认为不参与配分，因此其值置为零。该配分函数是 (Barone, eq. (59))\n",
    "\n",
    "$$\n",
    "\\theta_i (T) = \\left\\{\n",
    "\\begin{alignat}{3}\n",
    "& \\cot \\left( \\frac{h \\omega_i c_0}{2 k_\\mathrm{B} T} \\right) \\quad &&\\omega_i \\in \\mathbb{R} \\\\\n",
    "& 0 && \\omega_i \\in \\mathbb{I}\n",
    "\\end{alignat}\n",
    "\\right.\n",
    "$$\n",
    "\n",
    "在后续的文档中，我们始终会使用 $T_{2500} = 2500 \\ \\mathrm{K}$。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "3be15c44",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_coef_temp(T, calc_imag=False):\n",
    "    coef_temp = np.tanh(h * fa.freq * 100 * c_0 / (2 * k_B * T))**-1\n",
    "    if not calc_imag: coef_temp[coef_temp < 0] = 0\n",
    "    else: coef_temp = np.abs(coef_temp)\n",
    "    return coef_temp"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "570a0c11",
   "metadata": {},
   "source": [
    "显然，在 $0 \\ \\mathrm{K}$ 时，实数频率的 $\\theta_i (0) = 1$。在 $2500 \\ \\mathrm{K}$ 时，温度对简振坐标平均偏移的矫正比例 `coef_temp` 是"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "a05b9aaf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.      , 2.226801, 1.980529, 1.88035 , 1.240967, 1.1125  ])"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "T = 2500\n",
    "coef_temp = get_coef_temp(T)\n",
    "coef_temp"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5fb88d6",
   "metadata": {},
   "source": [
    "### 一阶简振坐标平均偏移的振动贡献"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea2d3571",
   "metadata": {},
   "source": [
    "我们假定虚频对谱学性质的计算不产生贡献。对于实数的简振模式 $i$，一阶的简振坐标平均偏移 $\\langle Q_i \\rangle^\\mathrm{vib}$ 为 (Barone, eq. (56))：\n",
    "\n",
    "$$\n",
    "\\langle Q_i \\rangle^\\mathrm{vib} (T) = - \\frac{\\hbar}{4 \\lambda_i} \\sum_j \\frac{\\Phi_{ijj}}{\\sqrt{|\\lambda_j|}} \\theta_j (T)\n",
    "$$\n",
    "\n",
    "我们将常用的转换系数置于变量 `Q_scale`，并令 $\\langle Q_i \\rangle^\\mathrm{vib} (0)$ 为 `Q_1`，$\\langle Q_i \\rangle^\\mathrm{vib} (T_{2500})$ 为 `QT_1`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "cbe1a4a3",
   "metadata": {},
   "outputs": [],
   "source": [
    "Q_scale = hbar / np.sqrt(E_h * a_0**2 * amu)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "fa5fc3f0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<Q> (0 K)    [ 0.        0.014627 -0.03185  -0.059824  0.01557   0.00532 ]\n",
      "<Q> (2500 K) [ 0.        0.026619 -0.055617 -0.11182   0.022404  0.005395]\n"
     ]
    }
   ],
   "source": [
    "Q_1, QT_1 = np.zeros(nvib), np.zeros(nvib)\n",
    "for i in range(nvib):\n",
    "    if fa.freq[i] <= 0: continue\n",
    "    for j in range(nvib):\n",
    "        val = - deriv_3[i,j,j] / (4 * lambd[i] * np.sqrt(np.abs(lambd[j]))) * Q_scale\n",
    "        Q_1[i] += val\n",
    "        QT_1[i] += val * coef_temp[j]\n",
    "print(\"<Q> (0 K)   \", Q_1)\n",
    "print(\"<Q> (2500 K)\", QT_1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0573c61",
   "metadata": {},
   "source": [
    "Gaussian 的结果显式如下。之所以会有正负号的差异，是因为我们的简振坐标方向会与 Gaussian 有些微区别。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "20e5d957",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Average Normal Coordinates (in amu^1/2.bohr)\r\n",
      " --------------------------------------------\r\n",
      "   Mode    <Q> (0)       <Q> (******)\r\n",
      "      2     0.005318        0.005392\r\n",
      "      3     0.015568        0.022402\r\n",
      "      4    -0.059824       -0.111821\r\n",
      "      5     0.031847        0.055613\r\n",
      "      6    -0.014626       -0.026617\r\n"
     ]
    }
   ],
   "source": [
    "! head -n 13347 anharm-G16B01.log | tail -n 8"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acd19f13",
   "metadata": {},
   "source": [
    ":::{danger}\n",
    "\n",
    "对于这里的实现，关于如何处理虚频，Gaussian 09 rev. D01 与 Gaussian 16 rev. B01 应是一致的，但与 Gaussian 09 rev. C01 不一致。两边似乎都有不合理之处。\n",
    "\n",
    "我们之前采用的是与 Gaussian 16 rev. B01 相似的做法。\n",
    "\n",
    "- 对于 Gaussian 09 rev. C01，它在计算温度矫正系数时，并没有排除虚频部分。同时，该版本还只能计算室温的温度效应。使用后一个被折叠的 code cell 即可给出该版本的结果。\n",
    "\n",
    "- 对于 Gaussian 16 rev. B01，尽管在 $2500 \\ \\mathrm{K}$ 时排除了虚频的贡献，但在 $0 \\ \\mathrm{K}$ 下仍然考虑了虚频；因此尽管说 $T_{2500}$ 是很高的温度，但 $\\langle Q_i \\rangle^\\mathrm{vib} (0)$ 与 $\\langle Q_i \\rangle^\\mathrm{vib} (T_{2500})$，甚至极端一些 $\\langle Q_i \\rangle^\\mathrm{vib} (1 \\ \\mathrm{K})$ 的差距还是会非常大。这种做法似乎也不合理。\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "d6a0db21",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<Q> (0 K)    [ 0.        0.014627 -0.03185  -0.059824  0.01557   0.00532 ]\n",
      "<Q> (298 K)  [ 0.        0.014657 -0.031826 -0.059851  0.015479  0.005218]\n"
     ]
    }
   ],
   "source": [
    "def print_Q_1_G09C01():\n",
    "    coef_temp_G09C01 = np.abs(get_coef_temp(298, calc_imag=True))\n",
    "    Q_1, QT_1 = np.zeros(nvib), np.zeros(nvib)\n",
    "    for i in range(nvib):\n",
    "        if fa.freq[i] <= 0: continue\n",
    "        for j in range(nvib):\n",
    "            val = - deriv_3[i,j,j] / (4 * lambd[i] * np.sqrt(np.abs(lambd[j]))) * Q_scale\n",
    "            Q_1[i] += val\n",
    "            QT_1[i] += val * coef_temp_G09C01[j]\n",
    "    print(\"<Q> (0 K)   \", Q_1)\n",
    "    print(\"<Q> (298 K) \", QT_1)\n",
    "print_Q_1_G09C01()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f45634a",
   "metadata": {},
   "source": [
    "### 二阶简振坐标平均偏移的振动贡献"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff4d9f60",
   "metadata": {},
   "source": [
    "对于实数的简振模式 $i$，一阶的简振坐标平均偏移 $\\langle Q_i Q_j \\rangle$ 只有在 $i = j$ 时非零。因此，我们只需要考虑 $\\langle Q_i^2 \\rangle (T)$ (Barone, eq. (56))：\n",
    "\n",
    "$$\n",
    "\\langle Q_i^2 \\rangle (T) = \\frac{\\hbar}{2 \\sqrt{\\lambda_i}}\n",
    "$$\n",
    "\n",
    "我们令 $\\langle Q_i^2 \\rangle (0)$ 为 `Q_2`，$\\langle Q_i^2 \\rangle (T_{2500})$ 为 `QT_2`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "3e60457a",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.       0.035825 0.031163 0.029228 0.015536 0.011814]\n",
      "[0.       0.079775 0.061719 0.054959 0.01928  0.013143]\n"
     ]
    }
   ],
   "source": [
    "Q_2, QT_2 = np.zeros(nvib), np.zeros(nvib)\n",
    "for i in range(nvib):\n",
    "    if fa.freq[i] <= 0: continue\n",
    "    val = 1 / (2 * np.sqrt(lambd[i])) * Q_scale\n",
    "    Q_2[i] += val\n",
    "    QT_2[i] += val * coef_temp[i]\n",
    "print(Q_2)\n",
    "print(QT_2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f709fabc",
   "metadata": {},
   "source": [
    "Gaussian 的结果显式如下。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "9321c45c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Mean Square Amplitudes of Normal Coordinates (in amu.bohr^2)\r\n",
      " -----------------------------------------------------------\r\n",
      " Mode    <Q^2> (0)    <Q^2> (******)    <Q^2> (******) class.\r\n",
      "    2     0.011814       0.013143          0.318060\r\n",
      "    3     0.015536       0.019280          0.550081\r\n",
      "    4     0.029228       0.054959          1.946911\r\n",
      "    5     0.031163       0.061719          2.213156\r\n",
      "    6     0.035825       0.079775          2.924904\r\n"
     ]
    }
   ],
   "source": [
    "! head -n 13338 anharm-G16B01.log | tail -n 8"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e32b59a",
   "metadata": {},
   "source": [
    ":::{danger}\n",
    "\n",
    "Barone 文章的 eq. (57) 公式很有可能差了一个正负号。因此上面的实现方式与 Barone 原文并不完全一致。在 Harding et al. [^Gauss.JCP.2008] 的 eq. (3) 中，就没有出现负号；因此多半与 Gaussian 的实现是一致的。在作这部分 Double Check 后，决定在这篇文档的程序实现中去除负号。\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26cd3727",
   "metadata": {},
   "source": [
    "## 非谐谱学性质：偶极矩"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b9ab954",
   "metadata": {},
   "source": [
    "现在我们考虑在非谐近似下，相对来说最简单的光谱性质，即偶极矩强度。\n",
    "\n",
    "我们在获得了简振坐标平均偏移量 $\\langle Q_i \\rangle$ 与 $\\langle Q_i^2 \\rangle$，且得到平衡构型下目标性质 $P$ 对简振坐标的导数后，就可以求取特定温度非谐近似下的目标性质的值：\n",
    "\n",
    "$$\n",
    "\\langle P \\rangle^\\mathrm{anharm} (T) \\simeq P + \\sum_i \\frac{\\partial P}{\\partial Q_i} \\cdot \\langle Q_i \\rangle (T) + \\frac{1}{2} \\sum_{i} \\frac{\\partial^2 P}{\\partial Q_i^2} \\cdot \\langle Q_i^2 \\rangle (T)\n",
    "$$\n",
    "\n",
    "尽管求取的方式并不复杂，但在获取程序输出时，仍然必须要格外当心。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ecacd6b0",
   "metadata": {},
   "source": [
    "### 偶极矩的高阶导数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a913c8aa",
   "metadata": {},
   "source": [
    "我们知道，为获得红外光谱数据，我们需要计算偶极在原子坐标下的导数 $\\partial \\boldsymbol{\\mu} / \\partial A_\\alpha$。在 Gaussian 中，只要进行频率分析 (求取能量的二阶导数)，就可以获得偶极矩的原子坐标导数。\n",
    "\n",
    "在 PySCF 中，尽管没有特定的函数去完成偶极矩的原子坐标导数的功能；但对于开壳层的自洽场计算方法，如果我们有了 Hessian 计算的实例，那么其求取实际上只需要 15 行代码左右。下述 `get_dipderiv` 通过带入闭壳层 Hessian 计算实例，给出偶极在原子坐标下的导数 $\\partial \\boldsymbol{\\mu} / \\partial A_\\alpha$ (维度：$(A, \\alpha, \\gamma)$，其中 $A_\\alpha$ 是原子坐标，$\\gamma$ 是偶极方向)。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "793db7c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_dipderiv(mf_hess):\n",
    "    mf, mol = mf_hess.base, mf_hess.mol\n",
    "    natm, nao, nocc = mol.natm, mol.nao, mol.nelec[0]\n",
    "    H_2_ao = np.zeros((3, natm, 3, nao, nao))\n",
    "    int1e_irp = mol.intor(\"int1e_irp\").reshape((3, 3, nao, nao))\n",
    "    for A in range(natm):\n",
    "        _, _, p0, p1 = mol.aoslice_by_atom()[A]\n",
    "        H_2_ao[:, A, :, :, p0:p1] = int1e_irp[:, :, :, p0:p1]\n",
    "    H_2_ao += H_2_ao.swapaxes(-1, -2)\n",
    "    dipderiv_skeleton = einsum(\"rAtuv, uv -> rAt\", H_2_ao, mf.make_rdm1())\n",
    "    dipderiv_nuc = einsum(\"rt, A -> rAt\", np.eye(3), mol.atom_charges())\n",
    "    h1ao = mf_hess.make_h1(mf.mo_coeff, mf.mo_occ)\n",
    "    mo1 = np.array(mf_hess.solve_mo1(mf.mo_energy, mf.mo_coeff, mf.mo_occ, h1ao)[0])\n",
    "    dipderiv_U = 4 * einsum(\"Atui, ruv, vi -> rAt\", mo1, - mol.intor(\"int1e_r\"), mf.mo_coeff[:, :nocc])\n",
    "    return (dipderiv_skeleton + dipderiv_nuc + dipderiv_U).reshape(3, 3 * natm).T"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d3c477e",
   "metadata": {},
   "source": [
    "在可以解析地计算偶极的核坐标导数之后，仿照先前求取能量对简振模量的高阶导数，我们很容易地给出偶极矩对简振坐标的数值二阶导数、以及一部分数值三阶导数。程序计算所使用的单位是偶极使用 $\\mathrm{Debye}$，简振坐标使用原子单位 $\\mathrm{Bohr \\ amu^{1/2}}$，所有偶极取向均变换到 Eckart Orientation。需要注意到我们无法求取完整的三阶导数，因此三阶导数量的维度与二阶相同。\n",
    "\n",
    "- `dip_0`：$\\mu_\\gamma$\n",
    "- `dip_1`：$\\partial \\mu_\\gamma / \\partial Q_i$，维度 $(i, \\gamma)$\n",
    "- `dip_2`：$\\partial^2 \\mu_\\gamma / \\partial Q_i \\partial Q_j$，维度 $(i, j, \\gamma)$\n",
    "- `dip_3`：$\\partial^3 \\mu_\\gamma / \\partial Q_i^2 \\partial Q_j$，维度 $(i, j, \\gamma)$\n",
    "\n",
    "这部分的结果可以与 Gaussian 16 rev. B01 作核验。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "daead030",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dipole moment(X, Y, Z, Debye): -0.01359, -0.52278,  0.07319\n"
     ]
    }
   ],
   "source": [
    "dip_0 = mf.dip_moment() @ fa.rot_vec\n",
    "dip_1 = einsum(\"Aα, αγ, Ai -> iγ\", get_dipderiv(mf_hess), fa.rot_vec, fa.q) * data.nist.AU2DEBYE\n",
    "dip_tmp_2 = NumericDiff(num_hess, lambda mf_hess: get_dipderiv(mf_hess)).derivative * data.nist.AU2DEBYE\n",
    "dip_2 = einsum(\"iAα, αγ, Aj -> ijγ\", dip_tmp_2, fa.rot_vec, fa.q)\n",
    "dipderiv_gathered = np.array([[get_dipderiv(mf_hess) for mf_hess in l] for l in num_hess.objects]) * data.nist.AU2DEBYE\n",
    "dip_tmp_3 = einsum(\"iσAα, αγ, Aj -> σijγ\", dipderiv_gathered, fa.rot_vec, fa.q)\n",
    "dip_3 = (dip_tmp_3[0] + dip_tmp_3[1] - 2 * dip_1) / (num_hess.interval**2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ab9cbde",
   "metadata": {},
   "source": [
    ":::{warning}\n",
    "\n",
    "Gaussian 09 rev. D01 版本中，偶极矩的取向对应输入分子所使用的坐标系；但 Gaussian 16 rev. B01 版本中，偶极的取向对应 Eckart Orientation。本文档使用后者；读者需要小心地处理坐标系取向。\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "669879f4",
   "metadata": {},
   "source": [
    "### 二阶非谐效应的偶极贡献"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1d26877",
   "metadata": {},
   "source": [
    "矫正项 $\\partial^2 \\mu_\\gamma / \\partial Q_i^2 \\cdot \\langle Q_i^2 \\rangle (T)$ 以维度为 $(i, \\alpha)$ 的矩阵表示如下：\n",
    "\n",
    "- `dip_anharm_2`：$T = 0$ 的情形\n",
    "- `dipT_anharm_2`：$T = T_{2500}$ 的情形"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "5a8f75da",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.      ,  0.      , -0.      ],\n",
       "       [ 0.002213, -0.001139, -0.000712],\n",
       "       [-0.004645,  0.001438,  0.000898],\n",
       "       [ 0.008767,  0.001811, -0.000082],\n",
       "       [-0.003475,  0.002666,  0.000128],\n",
       "       [-0.002509, -0.005047, -0.000059]])"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dip_anharm_2 = 0.5 * dip_2.diagonal(0, 0, 1).T * Q_2[:, None]\n",
    "dip_anharm_2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "7d6626be",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.      ,  0.      , -0.      ],\n",
       "       [ 0.004927, -0.002536, -0.001586],\n",
       "       [-0.0092  ,  0.002849,  0.001778],\n",
       "       [ 0.016485,  0.003405, -0.000155],\n",
       "       [-0.004312,  0.003309,  0.000159],\n",
       "       [-0.002791, -0.005614, -0.000066]])"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dipT_anharm_2 = 0.5 * dip_2.diagonal(0, 0, 1).T * QT_2[:, None]\n",
    "dipT_anharm_2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9d830e3",
   "metadata": {},
   "source": [
    "### 一阶振动非谐效应的偶极贡献"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9c0c891",
   "metadata": {},
   "source": [
    "矫正项 $\\partial \\mu_\\gamma / \\partial Q_i \\cdot \\langle Q_i \\rangle^\\mathrm{vib} (T)$ 以维度为 $(i, \\alpha)$ 的矩阵表示如下：\n",
    "\n",
    "- `dip_anharm_1`：$T = 0$ 的情形\n",
    "- `dipT_anharm_1`：$T = T_{2500}$ 的情形"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "7d9d1f20",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.      , -0.      , -0.      ],\n",
       "       [-0.000133,  0.004004, -0.000545],\n",
       "       [-0.004411,  0.005262,  0.000769],\n",
       "       [-0.013259, -0.008027, -0.000521],\n",
       "       [ 0.002164, -0.000338,  0.000207],\n",
       "       [ 0.000337,  0.000047,  0.000094]])"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dip_anharm_1 = dip_1 * Q_1[:, None]\n",
    "dip_anharm_1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "ce21ed1f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.      , -0.      , -0.      ],\n",
       "       [-0.000242,  0.007286, -0.000992],\n",
       "       [-0.007703,  0.009188,  0.001343],\n",
       "       [-0.024782, -0.015004, -0.000973],\n",
       "       [ 0.003114, -0.000487,  0.000299],\n",
       "       [ 0.000342,  0.000048,  0.000095]])"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dipT_anharm_1 = dip_1 * QT_1[:, None]\n",
    "dipT_anharm_1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13249c54",
   "metadata": {},
   "source": [
    ":::{danger}\n",
    "\n",
    "Gaussian 16 rev. B01 与 Gaussian 09 rev. D01 在一阶振动计算上都存在问题，且问题均为计算性质时所用的 $\\langle Q_i \\rangle^\\mathrm{vib} (T)$ 与先前计算的结果不同。\n",
    "\n",
    "我们回顾到，对于实数频率，\n",
    "\n",
    "$$\n",
    "\\langle Q_i \\rangle^\\mathrm{vib} (T) = - \\frac{\\hbar}{4 \\lambda_i} \\sum_j \\frac{\\Phi_{ijj}}{\\sqrt{|\\lambda_j|}} \\theta_j (T)\n",
    "$$\n",
    "\n",
    "但在 Gaussian 中的实现，很有可能是\n",
    "\n",
    "$$\n",
    "\\langle Q_i \\rangle^\\mathrm{vib} (T) = - \\frac{\\hbar}{4 \\lambda_i} \\sum_j \\frac{\\Phi_{ijj}}{\\sqrt{|\\lambda_j|}} \\theta_j (298.15 \\ \\mathrm{K}) \\theta_j (T)\n",
    "$$\n",
    "\n",
    "我认为这显然有些问题哈。\n",
    "\n",
    "下面被折叠的 code cell 可以复现 Gaussian 输出的结果。\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "66e5b7e7",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gaussian 16 rev. B01\n",
      "Temperature: 0 K\n",
      "[[-0.       -0.       -0.      ]\n",
      " [-0.000119  0.003575 -0.000487]\n",
      " [-0.004617  0.005507  0.000805]\n",
      " [-0.013046 -0.007899 -0.000512]\n",
      " [ 0.002838 -0.000443  0.000272]\n",
      " [ 0.000674  0.000094  0.000188]]\n",
      "Temperature: 2500 K\n",
      "[[-0.       -0.       -0.      ]\n",
      " [-0.000242  0.007287 -0.000993]\n",
      " [-0.007704  0.009189  0.001343]\n",
      " [-0.024786 -0.015006 -0.000973]\n",
      " [ 0.003113 -0.000487  0.000299]\n",
      " [ 0.000341  0.000048  0.000095]]\n",
      "=====\n",
      "Gaussian 09 rev. D01\n",
      "Temperature: 0 K\n",
      "[[ 0.        0.        0.      ]\n",
      " [-0.001651  0.000601  0.003154]\n",
      " [-0.006357 -0.001267  0.003206]\n",
      " [-0.008541 -0.001726 -0.012527]\n",
      " [ 0.002775  0.000134  0.000776]\n",
      " [ 0.000591 -0.000082  0.000378]]\n",
      "Temperature: 2500 K\n",
      "[[ 0.        0.        0.      ]\n",
      " [-0.003365  0.001224  0.006428]\n",
      " [-0.010607 -0.002114  0.00535 ]\n",
      " [-0.016227 -0.003279 -0.0238  ]\n",
      " [ 0.003045  0.000147  0.000851]\n",
      " [ 0.000299 -0.000042  0.000191]]\n"
     ]
    }
   ],
   "source": [
    "def dip_anharm_1_Gaussian():\n",
    "    Q_1, QT_1, QTT_1 = np.zeros(nvib), np.zeros(nvib), np.zeros(nvib)\n",
    "    for i in range(nvib):\n",
    "        if fa.freq[i] <= 0: continue\n",
    "        for j in range(nvib):\n",
    "            val = - deriv_3[i,j,j] / (4 * lambd[i] * np.sqrt(np.abs(lambd[j]))) * Q_scale\n",
    "            Q_1[i] += val\n",
    "            QT_1[i] += val * get_coef_temp(298.15)[j]\n",
    "            QTT_1[i] += val * get_coef_temp(298.15)[j] * get_coef_temp(T)[j]\n",
    "    print(\"Gaussian 16 rev. B01\")\n",
    "    print(\"Temperature: 0 K\")\n",
    "    print(dip_1 * QT_1[:, None])\n",
    "    print(\"Temperature: 2500 K\")\n",
    "    print(dip_1 * QTT_1[:, None])\n",
    "    print(\"=====\")\n",
    "    print(\"Gaussian 09 rev. D01\")\n",
    "    print(\"Temperature: 0 K\")\n",
    "    print(dip_1 * QT_1[:, None] @ fa.rot_vec.T)\n",
    "    print(\"Temperature: 2500 K\")\n",
    "    print(dip_1 * QTT_1[:, None] @ fa.rot_vec.T)\n",
    "dip_anharm_1_Gaussian()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "c1f3abef",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   ## Vibrational contributions to averages at    0K (Unit: Debye) ##\r\n",
      " ---------------------------------------------------------------------------\r\n",
      "          Mode |   P1(diag)     P1(vib)    P1(rot)        P2     |  P1(tot)+P2\r\n",
      " ---------------------------------------------------------------------------\r\n",
      " X           2 |   0.111D-02   0.674D-03   0.000D+00  -0.251D-02 |  -0.183D-02\r\n",
      " X           3 |   0.316D-02   0.284D-02   0.000D+00  -0.348D-02 |  -0.637D-03\r\n",
      " X           4 |  -0.898D-02  -0.130D-01   0.000D+00   0.877D-02 |  -0.428D-02\r\n",
      " X           5 |   0.664D-05  -0.462D-02   0.000D+00  -0.465D-02 |  -0.926D-02\r\n",
      " X           6 |   0.226D-04  -0.119D-03   0.000D+00   0.221D-02 |   0.209D-02\r\n",
      " Y           2 |   0.156D-03   0.944D-04   0.000D+00  -0.505D-02 |  -0.495D-02\r\n",
      " Y           3 |  -0.494D-03  -0.443D-03   0.000D+00   0.267D-02 |   0.222D-02\r\n",
      " Y           4 |  -0.544D-02  -0.790D-02   0.000D+00   0.181D-02 |  -0.609D-02\r\n",
      " Y           5 |  -0.793D-05   0.551D-02   0.000D+00   0.144D-02 |   0.694D-02\r\n",
      " Y           6 |  -0.681D-03   0.357D-02   0.000D+00  -0.114D-02 |   0.244D-02\r\n",
      " Z           2 |   0.310D-03   0.188D-03   0.000D+00  -0.591D-04 |   0.129D-03\r\n",
      " Z           3 |   0.303D-03   0.272D-03   0.000D+00   0.128D-03 |   0.400D-03\r\n",
      " Z           4 |  -0.352D-03  -0.512D-03   0.000D+00  -0.824D-04 |  -0.595D-03\r\n",
      " Z           5 |  -0.116D-05   0.805D-03   0.000D+00   0.898D-03 |   0.170D-02\r\n",
      " Z           6 |   0.927D-04  -0.487D-03   0.000D+00  -0.712D-03 |  -0.120D-02\r\n",
      " ---------------------------------------------------------------------------\r\n"
     ]
    }
   ],
   "source": [
    "! head -n 13449 anharm-G16B01.log | tail -n 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "1ab6fc74",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   ## Vibrational contributions to averages at 2500K (Unit: Debye) ##\r\n",
      " ---------------------------------------------------------------------------\r\n",
      "          Mode |   P1(diag)     P1(vib)    P1(rot)        P2     |  P1(tot)+P2\r\n",
      " ---------------------------------------------------------------------------\r\n",
      " X           2 |   0.111D-02   0.342D-03  -0.696D-05  -0.279D-02 |  -0.246D-02\r\n",
      " X           3 |   0.316D-02   0.311D-02   0.252D-04  -0.431D-02 |  -0.117D-02\r\n",
      " X           4 |  -0.898D-02  -0.248D-01  -0.115D-03   0.165D-01 |  -0.841D-02\r\n",
      " X           5 |   0.664D-05  -0.770D-02   0.656D-03  -0.920D-02 |  -0.162D-01\r\n",
      " X           6 |   0.226D-04  -0.242D-03   0.104D-04   0.493D-02 |   0.470D-02\r\n",
      " Y           2 |   0.156D-03   0.478D-04  -0.974D-06  -0.561D-02 |  -0.557D-02\r\n",
      " Y           3 |  -0.494D-03  -0.487D-03  -0.394D-05   0.331D-02 |   0.282D-02\r\n",
      " Y           4 |  -0.544D-02  -0.150D-01  -0.698D-04   0.340D-02 |  -0.117D-01\r\n",
      " Y           5 |  -0.793D-05   0.919D-02  -0.782D-03   0.285D-02 |   0.113D-01\r\n",
      " Y           6 |  -0.681D-03   0.729D-02  -0.167D-03  -0.254D-02 |   0.458D-02\r\n",
      " Z           2 |   0.310D-03   0.950D-04  -0.194D-05  -0.658D-04 |   0.273D-04\r\n",
      " Z           3 |   0.303D-03   0.299D-03   0.242D-05   0.159D-03 |   0.460D-03\r\n",
      " Z           4 |  -0.352D-03  -0.973D-03  -0.452D-05  -0.155D-03 |  -0.113D-02\r\n",
      " Z           5 |  -0.116D-05   0.134D-02  -0.114D-03   0.178D-02 |   0.301D-02\r\n",
      " Z           6 |   0.927D-04  -0.992D-03   0.228D-04  -0.159D-02 |  -0.256D-02\r\n",
      " ---------------------------------------------------------------------------\r\n"
     ]
    }
   ],
   "source": [
    "! head -n 13479 anharm-G16B01.log | tail -n 20"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "50fdfdb8",
   "metadata": {},
   "source": [
    "### 一阶转动非谐效应的偶极贡献"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0496e06a",
   "metadata": {},
   "source": [
    "我们现在考虑一阶转动的非谐效应。实际上，依据 Harding et al. [^Gauss.JCP.2008] eq. (4)，一阶简谐模量的平均偏移不止有振动的贡献，也还有转动的贡献：\n",
    "\n",
    "$$\n",
    "\\langle Q_i \\rangle (T) = \\langle Q_i \\rangle^\\mathrm{vib} (T) + \\langle Q_i \\rangle^\\mathrm{rot} (T) = - \\frac{\\hbar}{4 \\lambda_i} \\sum_j \\frac{\\Phi_{ijj}}{\\sqrt{|\\lambda_j|}} \\theta_j (T) + \\frac{k_\\mathrm{B} T}{2 \\lambda_i} \\sum_\\alpha \\frac{\\partial I_{\\alpha \\alpha}}{\\partial Q_i} \\frac{1}{I_{\\alpha \\alpha}}\n",
    "$$\n",
    "\n",
    "为此，我们还需要求取转动惯量 $I_{\\alpha \\beta}$ 在简振坐标下的导数 $\\partial I_{\\alpha \\beta}$ `deriv_inertia` (维度：$(i, \\alpha, \\beta)$)。需要注意的是，尽管我们已经将分子转动到 Eckart Orientation 以使得转动惯量矩阵是对角矩阵 $I_{\\alpha \\beta} = \\delta_{\\alpha \\beta} I_{\\alpha \\alpha}$，但这不意味着其简振坐标下的导数还是对角的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "a2b3c435",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_fa(mf_hess):\n",
    "    mol = mf_hess.mol\n",
    "    fa = FreqAnal()\n",
    "    fa.mol_weights = get_atom_mass_list(mol)\n",
    "    fa.mol_coords = mol.atom_coords()\n",
    "    fa.natm = mol.natm\n",
    "    fa.mol_hess = mf_hess.de.swapaxes(1, 2)\n",
    "    return fa"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "ac4b84e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "deriv_inertia = NumericDiff(num_hess, lambda mf_hess: get_fa(mf_hess).mom_inertia).derivative\n",
    "deriv_inertia = einsum(\"Aγδ, γα, δβ -> Aαβ\", deriv_inertia, fa.rot_vec, fa.rot_vec)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9a62d3e",
   "metadata": {},
   "source": [
    "依据这个导数，在合理的单位转换下，我们能给出 $\\langle Q_i \\rangle^\\mathrm{vib} (T_{2500})$ `QTrot_1`。同时，我们也能看到，显然地 $\\langle Q_i \\rangle^\\mathrm{vib} (0)$ `Qrot_1` 为零，因此在 $0 \\ \\mathrm{K}$ 下，分子旋转对非谐效应不产生贡献。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "b0fccef6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.      ,  0.005706, -0.006855, -0.025615,  0.006727,  0.003773])"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "QTrot_1 = (1/2 * T * k_B / lambd * (deriv_inertia.diagonal(0, -1, -2) / (fa.rot_eig)).sum(axis=-1)) * E_h**-1\n",
    "QTrot_1[lambd < 0] = 0\n",
    "Qrot_1 = np.zeros_like(QTrot_1)\n",
    "QTrot_1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75896a27",
   "metadata": {},
   "source": [
    "矫正项 $\\partial \\mu_\\gamma / \\partial Q_i \\cdot \\langle Q_i \\rangle^\\mathrm{rot} (T)$ 以维度为 $(i, \\alpha)$ 的矩阵表示如下：\n",
    "\n",
    "- `dip_anharm_rot`：$T = 0$ 的情形 (实际上 $0 \\ \\mathrm{K}$ 不产生贡献)\n",
    "- `dipT_anharm_rot`：$T = T_{2500}$ 的情形"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "d1e4e88c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.      , -0.      , -0.      ],\n",
       "       [-0.000052,  0.001562, -0.000213],\n",
       "       [-0.000949,  0.001132,  0.000166],\n",
       "       [-0.005677, -0.003437, -0.000223],\n",
       "       [ 0.000935, -0.000146,  0.00009 ],\n",
       "       [ 0.000239,  0.000033,  0.000066]])"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dipT_anharm_rot = QTrot_1[:, None] * dip_1\n",
    "dip_anharm_rot = np.zeros_like(dipT_anharm_rot)\n",
    "dipT_anharm_rot"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "112a8f8f",
   "metadata": {},
   "source": [
    "旋转的贡献一般来说总是比振动小不少。在 Gaussian 09 版本中，实际上就没有考虑转动的贡献；尽管不太精确，但作这种忽略也应认为是合理的。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5be20434",
   "metadata": {},
   "source": [
    ":::{danger}\n",
    "\n",
    "Gaussian 16 rev. B01 的转动贡献计算很可能是错误的。该错误不容易重现。\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31d8987c",
   "metadata": {},
   "source": [
    "### 统合所有贡献"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aaa11d59",
   "metadata": {},
   "source": [
    "回顾到非谐性质在简振坐标下的展开式\n",
    "\n",
    "$$\n",
    "\\langle P \\rangle^\\mathrm{anharm} (T) \\simeq P + \\sum_i \\frac{\\partial P}{\\partial Q_i} \\cdot \\langle Q_i \\rangle (T) + \\frac{1}{2} \\sum_{i} \\frac{\\partial^2 P}{\\partial Q_i^2} \\cdot \\langle Q_i^2 \\rangle (T)\n",
    "$$\n",
    "\n",
    "在所有贡献量都已经求得的情况下，我们很容易地给出 $0 \\ \\mathrm{K}$ 与 $T_{2500} = 2500 \\ \\mathrm{K}$ 的非谐矫正下的偶极矩。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87e964c2",
   "metadata": {},
   "source": [
    "未矫正的偶极矩："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "ef1e9c5b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dipole/Debye (Uncorrected, Eckart Orientation):  [-0.059826  0.052123  0.522057]\n",
      "Dipole/Debye (Uncorrected, Input  Orientation):  [-0.013591 -0.522779  0.07319 ]\n"
     ]
    }
   ],
   "source": [
    "print(\"Dipole/Debye (Uncorrected, Eckart Orientation): \", dip_0)\n",
    "print(\"Dipole/Debye (Uncorrected, Input  Orientation): \", dip_0 @ fa.rot_vec.T)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3702c3d9",
   "metadata": {},
   "source": [
    "$0 \\ \\mathrm{K}$ 的非谐矫正偶极矩："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "6e9fccc1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dipole/Debye (0 K, Eckart Orientation):  [-0.074777  0.052801  0.522232]\n",
      "Dipole/Debye (0 K, Input  Orientation):  [-0.027333 -0.525138  0.067748]\n"
     ]
    }
   ],
   "source": [
    "dip_anharm = dip_0 + (dip_anharm_1 + dip_anharm_rot + dip_anharm_2).sum(axis=0)\n",
    "print(\"Dipole/Debye (0 K, Eckart Orientation): \", dip_anharm)\n",
    "print(\"Dipole/Debye (0 K, Input  Orientation): \", dip_anharm @ fa.rot_vec.T)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "031e449f",
   "metadata": {},
   "source": [
    "$T_{2500} = 2500 \\ \\mathrm{K}$ 的非谐矫正偶极矩："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "b3295ef7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dipole/Debye (0 K, Eckart Orientation):  [-0.089493  0.053711  0.521843]\n",
      "Dipole/Debye (0 K, Input  Orientation):  [-0.041028 -0.526894  0.062559]\n"
     ]
    }
   ],
   "source": [
    "dipT_anharm = dip_0 + (dipT_anharm_1 + dipT_anharm_rot + dipT_anharm_2).sum(axis=0)\n",
    "print(\"Dipole/Debye (0 K, Eckart Orientation): \", dipT_anharm)\n",
    "print(\"Dipole/Debye (0 K, Input  Orientation): \", dipT_anharm @ fa.rot_vec.T)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "caa5fb91",
   "metadata": {},
   "source": [
    "## 非谐谱学性质：红外光谱"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85348fb5",
   "metadata": {},
   "source": [
    "如果上面用于计算偶极矩的计算方法也可以用于计算偶极矩的坐标导数，那么红外光谱也可以通过类似的方法实现。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7874907e",
   "metadata": {},
   "source": [
    ":::{danger}\n",
    "\n",
    "这只是依葫芦画瓢，用计算非谐偶极的方法套用到红外光谱中。很显然这未必是正确的，而且事实上，不仅是非谐振动频率 (因为 Fermi 或 Darling-Dennsion 共振)，**下述代码的 IR 峰强度结果也与 Gaussian 的输出非常不同**。\n",
    "\n",
    "因此，各位看官就当看个热闹哈 (｀・ω・´)\n",
    "\n",
    "想要了解更多信息，请参考 Bloino 作为第一作者的文章 ([^Bloino.JCP.2012], [^Bloino.JPCA.2015])。红外光谱应当需要作更严格的 RSPT 二阶展开，并且考虑一部分非基频振动间的相互跃迁偶极矩导数。这部分工作应当已经实现在 Gaussian 16 rev. B01 中，因此我们能获得非谐红外信息。\n",
    "\n",
    "在上面对 Gaussian 程序的实现结果作讨论之后，我其实觉得务实看待 Gaussian 输出的态度应当是保留地接受它。它所给出的分子振动频率还是相对准确的，特别是相比与本文档而言，对频率共振的处理多少让结果变好一些 (尽管对于 Fermi 共振，如果不应用 DCPT2 或其它简并微扰理论而完全去除共振项，任意性其实太强；这在 Gaussian 中或许实现了，但我还不清楚)。但在偶极矩 (或可能地，磁矩等) 的非谐处理上，大概还有需改进之处。\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1dc02bc5",
   "metadata": {},
   "source": [
    "我们这里选择使用相对来说较为真实的乙醛分子 (CH<sub>3</sub>CHO) 分子，作为绘制红外光谱的分子。计算方法仍然是 STO-3G。由于我们需要重新写一遍近乎完整的代码来绘制红外光谱，因此这里将大部分代码进行了折叠。其输入卡 {download}`CH3CHO.gjf`，输出文件 {download}`CH3CHO.log`。绘制红外光谱时，使用 Lorentzian 展宽，半峰宽 $30 \\ \\mathrm{cm^{-1}}$。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "91c0d877",
   "metadata": {},
   "source": [
    "### 分子定义与原子核高阶导数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "aee8c371",
   "metadata": {},
   "outputs": [],
   "source": [
    "mol = gto.Mole(atom=\"\"\"\n",
    "C   -0.852693    0.499814   -0.000294\n",
    "C    0.685096    0.670458    0.000342\n",
    "O    1.340323   -0.602319   -0.000432\n",
    "O   -1.349649   -0.611839    0.000139\n",
    "H   -1.450829    1.425645   -0.001000\n",
    "H    0.974215    1.253523    0.883979\n",
    "H    0.975003    1.254674   -0.882236\n",
    "H    0.581799   -1.242205    0.001322\n",
    "\"\"\", basis=\"STO-3G\", verbose=0).build()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "77ea3533",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "natm = mol.natm\n",
    "nhess = natm * 3\n",
    "mf = scf.RHF(mol).run()\n",
    "mf_hess = mf.Hessian().run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "b2e15cde",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "fa = FreqAnal()\n",
    "fa.mol_weights = get_atom_mass_list(mol)\n",
    "fa.mol_coords = mol.atom_coords()\n",
    "fa.natm = mol.natm\n",
    "fa.mol_hess = mf_hess.de.swapaxes(1, 2)\n",
    "nvib = fa.freq.size"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "f7f80101",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "deriv_2 = einsum(\"Pi, PQ, Qj -> ij\", fa.q, fa.mol_hess.reshape(nhess, nhess), fa.q)\n",
    "lambd = deriv_2.diagonal()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "0b5454c6",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "num_hess = ModeDerivGenerator(mol, lambda mol: scf.RHF(mol).run().Hessian().run(), fa.q, interval=0.01)\n",
    "tmp_3 = NumericDiff(num_hess, lambda mf: mf.de.swapaxes(1, 2).reshape(nhess, nhess)).derivative\n",
    "deriv_3 = einsum(\"Ai, Bj, kAB -> ijk\", fa.q, fa.q, tmp_3)\n",
    "deriv_3 = 1/3 * (deriv_3 + deriv_3.transpose(1, 2, 0) + deriv_3.transpose(2, 0, 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "132fa4b0",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "hess_gathered = np.array([[mf.de.swapaxes(1, 2).reshape(nhess, nhess) for mf in l] for l in num_hess.objects])\n",
    "tmp_4 = einsum(\"ksAB, Ai, Bj -> skij\", hess_gathered, fa.q, fa.q)\n",
    "deriv_4 = (tmp_4[0] + tmp_4[1] - 2 * deriv_2) / (num_hess.interval**2)  # finite diff\n",
    "deriv_4 = (deriv_4 + deriv_4.swapaxes(-1, -2)) / 2                      # symmetrize\n",
    "deriv_4 = einsum(\"kij -> ijk\", deriv_4)                                 # subscript transform"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8453936f",
   "metadata": {},
   "source": [
    "### $\\xi_{ij}$ 矩阵生成与非谐频率计算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "a3c4d6a7",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "xmat_4 = np.zeros((nvib, nvib))\n",
    "for i in range(nvib):\n",
    "    xmat_4[i, i] = deriv_4[i,i,i] / (16 * lambd[i])\n",
    "    for j in range(nvib):\n",
    "        if i == j: continue\n",
    "        xmat_4[i, j] = deriv_4[i,i,j] / (4 * np.sqrt(np.abs(lambd[i] * lambd[j])))\n",
    "xmat_4 *= (hbar / (2 * np.pi * c_0)) * (a_0**-2 * amu**-1) / (100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "d4f59bf5",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "xmat_3 = np.zeros((nvib, nvib))\n",
    "for i in range(nvib):\n",
    "    xmat_3[i, i] -= deriv_3[i,i,i]**2 * 5 / (3 * lambd[i])\n",
    "    for j in range(nvib):\n",
    "        if i == j: continue\n",
    "        xmat_3[i, i] -= deriv_3[i,i,j]**2 * (8 * lambd[i] - 3 * lambd[j]) / (lambd[j] * (4 * lambd[i] - lambd[j]))\n",
    "    xmat_3[i, i] /= 16 * lambd[i]\n",
    "for i in range(nvib):\n",
    "    for j in range(nvib):\n",
    "        if i == j: continue\n",
    "        xmat_3[i, j] -= deriv_3[i,i,j]**2 * 2 / (4 * lambd[i] - lambd[j])\n",
    "        xmat_3[i, j] -= deriv_3[i,j,j]**2 * 2 / (4 * lambd[j] - lambd[i])\n",
    "        xmat_3[i, j] -= deriv_3[i,i,i] * deriv_3[i,j,j] / lambd[i]\n",
    "        xmat_3[i, j] -= deriv_3[j,j,j] * deriv_3[i,i,j] / lambd[j]\n",
    "        for k in range(nvib):\n",
    "            if len(set([i, j, k])) != 3: continue\n",
    "            delta_ijk = lambd[i]**2 + lambd[j]**2 + lambd[k]**2 - 2 * (lambd[i]*lambd[j] + lambd[j]*lambd[k] + lambd[k]*lambd[i])\n",
    "            xmat_3[i, j] += deriv_3[i,j,k]**2 * 2 * (lambd[i] + lambd[j] - lambd[k]) / delta_ijk\n",
    "            xmat_3[i, j] -= deriv_3[i,i,k] * deriv_3[j,j,k] / lambd[k]\n",
    "        xmat_3[i, j] /= 4 * np.sqrt(np.abs(lambd[i] * lambd[j]))\n",
    "xmat_3 *= (hbar / (2 * np.pi * c_0)) * (a_0**-2 * amu**-1) / (100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "80a561a3",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "rot_wavenum = h / (8 * np.pi**2 * c_0 * fa.rot_eig) * (a_0**-2 * amu**-1) / (100)\n",
    "q_ = einsum(\"Aβi, βα, A -> Aαi\", fa.q.reshape(natm, 3, nvib), fa.rot_vec, np.sqrt(get_atom_mass_list(mol)))\n",
    "zeta_x = einsum(\"Ai, Aj -> ij\", q_[:, 1, :], q_[:, 2, :]) - einsum(\"Ai, Aj -> ij\", q_[:, 2, :], q_[:, 1, :])\n",
    "zeta_y = einsum(\"Ai, Aj -> ij\", q_[:, 2, :], q_[:, 0, :]) - einsum(\"Ai, Aj -> ij\", q_[:, 0, :], q_[:, 2, :])\n",
    "zeta_z = einsum(\"Ai, Aj -> ij\", q_[:, 0, :], q_[:, 1, :]) - einsum(\"Ai, Aj -> ij\", q_[:, 1, :], q_[:, 0, :])\n",
    "zeta = np.array([zeta_x, zeta_y, zeta_z])\n",
    "\n",
    "xmat_coriol = np.zeros((nvib, nvib))\n",
    "for i in range(nvib):\n",
    "    for j in range(nvib):\n",
    "        for ixyz in range(3):\n",
    "            xmat_coriol[i, j] += zeta[ixyz, i, j]**2 * rot_wavenum[ixyz]\n",
    "        xmat_coriol[i, j] *= (lambd[i] + lambd[j]) / np.sqrt(np.abs(lambd[i] * lambd[j]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "80d9febd",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "xmat = xmat_4 + xmat_3 + xmat_coriol\n",
    "freq_anharm = fa.freq + 1.5 * xmat.diagonal() + 0.5 * xmat.sum(axis=-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9aaccd33",
   "metadata": {},
   "source": [
    "### 温度效应矫正系数计算 (2500 K)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "8f3d1a9c",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "T = 2500\n",
    "coef_temp = get_coef_temp(T)\n",
    "Q_scale = hbar / np.sqrt(E_h * a_0**2 * amu)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "id": "d9eb69c1",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "Q_1, QT_1 = np.zeros(nvib), np.zeros(nvib)\n",
    "for i in range(nvib):\n",
    "    if fa.freq[i] <= 0: continue\n",
    "    for j in range(nvib):\n",
    "        val = - deriv_3[i,j,j] / (4 * lambd[i] * np.sqrt(np.abs(lambd[j]))) * Q_scale\n",
    "        Q_1[i] += val\n",
    "        QT_1[i] += val * coef_temp[j]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "effb8187",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "Q_2, QT_2 = np.zeros(nvib), np.zeros(nvib)\n",
    "for i in range(nvib):\n",
    "    if fa.freq[i] <= 0: continue\n",
    "    val = 1 / (2 * np.sqrt(lambd[i])) * Q_scale\n",
    "    Q_2[i] += val\n",
    "    QT_2[i] += val * coef_temp[i]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "id": "b95c3c22",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "deriv_inertia = NumericDiff(num_hess, lambda mf_hess: get_fa(mf_hess).mom_inertia).derivative\n",
    "deriv_inertia = einsum(\"Aγδ, γα, δβ -> Aαβ\", deriv_inertia, fa.rot_vec, fa.rot_vec)\n",
    "QTrot_1 = (1/2 * T * k_B / lambd * (deriv_inertia.diagonal(0, -1, -2) / (fa.rot_eig)).sum(axis=-1)) * E_h**-1\n",
    "QTrot_1[lambd < 0] = 0\n",
    "Qrot_1 = np.zeros_like(QTrot_1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca03ac9c",
   "metadata": {},
   "source": [
    "### 偶极矩导数与红外强度计算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "f5342f10",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dipole moment(X, Y, Z, Debye): -0.85484,  1.70251,  0.00242\n"
     ]
    }
   ],
   "source": [
    "dip_0 = mf.dip_moment() @ fa.rot_vec\n",
    "dip_1 = einsum(\"Aα, αγ, Ai -> iγ\", get_dipderiv(mf_hess), fa.rot_vec, fa.q) * data.nist.AU2DEBYE\n",
    "dip_tmp_2 = NumericDiff(num_hess, lambda mf_hess: get_dipderiv(mf_hess)).derivative * data.nist.AU2DEBYE\n",
    "dip_2 = einsum(\"iAα, αγ, Aj -> ijγ\", dip_tmp_2, fa.rot_vec, fa.q)\n",
    "dipderiv_gathered = np.array([[get_dipderiv(mf_hess) for mf_hess in l] for l in num_hess.objects]) * data.nist.AU2DEBYE\n",
    "dip_tmp_3 = einsum(\"iσAα, αγ, Aj -> σijγ\", dipderiv_gathered, fa.rot_vec, fa.q)\n",
    "dip_3 = (dip_tmp_3[0] + dip_tmp_3[1] - 2 * dip_1) / (num_hess.interval**2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "id": "c405c884",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "IR_scale = 1/3 * np.pi * F**2 * data.nist.AU2DEBYE**-2 * 1e-7\n",
    "IR_inten = (dip_1**2).sum(axis=-1) * IR_scale"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "bbe8853f",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "dip_1_anharm = einsum(\"ijγ, j -> jγ\", dip_2, Q_1 + Qrot_1) + 0.5 * einsum(\"ijγ, j -> jγ\", dip_3, Q_2)\n",
    "IR_anharm = ((dip_1 + dip_1_anharm)**2).sum(axis=-1) * IR_scale"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "id": "c08b6c0e",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "dip_1T_anharm = einsum(\"ijγ, j -> jγ\", dip_2, QT_1 + QTrot_1) + 0.5 * einsum(\"ijγ, j -> jγ\", dip_3, QT_2)\n",
    "IRT_anharm = ((dip_1 + dip_1T_anharm)**2).sum(axis=-1) * IR_scale"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3d5a21b",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "source": [
    "### 红外光谱绘制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "id": "e302752e",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "def lorentzian_freq(omega, omega_n, gamma):\n",
    "    return 100 * 0.5 / np.pi * gamma / ((omega - omega_n)**2 + 0.25 * gamma**2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "id": "27d6f96a",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "def ir_plot(omega, gamma, freq, ir):\n",
    "    val = 0\n",
    "    assert(len(freq) == len(ir))\n",
    "    for i in range(len(freq)):\n",
    "        val += lorentzian_freq(omega, freq[i], gamma) * ir[i]\n",
    "    return val"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "5a1a482d",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "freq_anharm_gau = [4098.800, 3570.604, 3446.746, 3471.841, 2088.048, 1787.600, 1725.346, 1593.897, 1530.767, 1407.142, 1297.110, 1206.649, 1019.526, 878.962, 795.699, 185.138, 258.388, 69.977]\n",
    "IR_anharm_gau = [2.37219675, 1.54485433, 9.30810815, 7.71760501, 22.32308331, 0.91999625, 21.74763306, 0.33568248, 39.89748639, 0.34998748, 8.84110221, 1.90263087, 8.44102685, 0.12421802, 12.58976516, 36.74388344, 9.13647155, 24.14833335]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "id": "4f6ed397",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "data": {
      "application/javascript": [
       "/* Put everything inside the global mpl namespace */\n",
       "/* global mpl */\n",
       "window.mpl = {};\n",
       "\n",
       "mpl.get_websocket_type = function () {\n",
       "    if (typeof WebSocket !== 'undefined') {\n",
       "        return WebSocket;\n",
       "    } else if (typeof MozWebSocket !== 'undefined') {\n",
       "        return MozWebSocket;\n",
       "    } else {\n",
       "        alert(\n",
       "            'Your browser does not have WebSocket support. ' +\n",
       "                'Please try Chrome, Safari or Firefox ≥ 6. ' +\n",
       "                'Firefox 4 and 5 are also supported but you ' +\n",
       "                'have to enable WebSockets in about:config.'\n",
       "        );\n",
       "    }\n",
       "};\n",
       "\n",
       "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n",
       "    this.id = figure_id;\n",
       "\n",
       "    this.ws = websocket;\n",
       "\n",
       "    this.supports_binary = this.ws.binaryType !== undefined;\n",
       "\n",
       "    if (!this.supports_binary) {\n",
       "        var warnings = document.getElementById('mpl-warnings');\n",
       "        if (warnings) {\n",
       "            warnings.style.display = 'block';\n",
       "            warnings.textContent =\n",
       "                'This browser does not support binary websocket messages. ' +\n",
       "                'Performance may be slow.';\n",
       "        }\n",
       "    }\n",
       "\n",
       "    this.imageObj = new Image();\n",
       "\n",
       "    this.context = undefined;\n",
       "    this.message = undefined;\n",
       "    this.canvas = undefined;\n",
       "    this.rubberband_canvas = undefined;\n",
       "    this.rubberband_context = undefined;\n",
       "    this.format_dropdown = undefined;\n",
       "\n",
       "    this.image_mode = 'full';\n",
       "\n",
       "    this.root = document.createElement('div');\n",
       "    this.root.setAttribute('style', 'display: inline-block');\n",
       "    this._root_extra_style(this.root);\n",
       "\n",
       "    parent_element.appendChild(this.root);\n",
       "\n",
       "    this._init_header(this);\n",
       "    this._init_canvas(this);\n",
       "    this._init_toolbar(this);\n",
       "\n",
       "    var fig = this;\n",
       "\n",
       "    this.waiting = false;\n",
       "\n",
       "    this.ws.onopen = function () {\n",
       "        fig.send_message('supports_binary', { value: fig.supports_binary });\n",
       "        fig.send_message('send_image_mode', {});\n",
       "        if (fig.ratio !== 1) {\n",
       "            fig.send_message('set_dpi_ratio', { dpi_ratio: fig.ratio });\n",
       "        }\n",
       "        fig.send_message('refresh', {});\n",
       "    };\n",
       "\n",
       "    this.imageObj.onload = function () {\n",
       "        if (fig.image_mode === 'full') {\n",
       "            // Full images could contain transparency (where diff images\n",
       "            // almost always do), so we need to clear the canvas so that\n",
       "            // there is no ghosting.\n",
       "            fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n",
       "        }\n",
       "        fig.context.drawImage(fig.imageObj, 0, 0);\n",
       "    };\n",
       "\n",
       "    this.imageObj.onunload = function () {\n",
       "        fig.ws.close();\n",
       "    };\n",
       "\n",
       "    this.ws.onmessage = this._make_on_message_function(this);\n",
       "\n",
       "    this.ondownload = ondownload;\n",
       "};\n",
       "\n",
       "mpl.figure.prototype._init_header = function () {\n",
       "    var titlebar = document.createElement('div');\n",
       "    titlebar.classList =\n",
       "        'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n",
       "    var titletext = document.createElement('div');\n",
       "    titletext.classList = 'ui-dialog-title';\n",
       "    titletext.setAttribute(\n",
       "        'style',\n",
       "        'width: 100%; text-align: center; padding: 3px;'\n",
       "    );\n",
       "    titlebar.appendChild(titletext);\n",
       "    this.root.appendChild(titlebar);\n",
       "    this.header = titletext;\n",
       "};\n",
       "\n",
       "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n",
       "\n",
       "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n",
       "\n",
       "mpl.figure.prototype._init_canvas = function () {\n",
       "    var fig = this;\n",
       "\n",
       "    var canvas_div = (this.canvas_div = document.createElement('div'));\n",
       "    canvas_div.setAttribute(\n",
       "        'style',\n",
       "        'border: 1px solid #ddd;' +\n",
       "            'box-sizing: content-box;' +\n",
       "            'clear: both;' +\n",
       "            'min-height: 1px;' +\n",
       "            'min-width: 1px;' +\n",
       "            'outline: 0;' +\n",
       "            'overflow: hidden;' +\n",
       "            'position: relative;' +\n",
       "            'resize: both;'\n",
       "    );\n",
       "\n",
       "    function on_keyboard_event_closure(name) {\n",
       "        return function (event) {\n",
       "            return fig.key_event(event, name);\n",
       "        };\n",
       "    }\n",
       "\n",
       "    canvas_div.addEventListener(\n",
       "        'keydown',\n",
       "        on_keyboard_event_closure('key_press')\n",
       "    );\n",
       "    canvas_div.addEventListener(\n",
       "        'keyup',\n",
       "        on_keyboard_event_closure('key_release')\n",
       "    );\n",
       "\n",
       "    this._canvas_extra_style(canvas_div);\n",
       "    this.root.appendChild(canvas_div);\n",
       "\n",
       "    var canvas = (this.canvas = document.createElement('canvas'));\n",
       "    canvas.classList.add('mpl-canvas');\n",
       "    canvas.setAttribute('style', 'box-sizing: content-box;');\n",
       "\n",
       "    this.context = canvas.getContext('2d');\n",
       "\n",
       "    var backingStore =\n",
       "        this.context.backingStorePixelRatio ||\n",
       "        this.context.webkitBackingStorePixelRatio ||\n",
       "        this.context.mozBackingStorePixelRatio ||\n",
       "        this.context.msBackingStorePixelRatio ||\n",
       "        this.context.oBackingStorePixelRatio ||\n",
       "        this.context.backingStorePixelRatio ||\n",
       "        1;\n",
       "\n",
       "    this.ratio = (window.devicePixelRatio || 1) / backingStore;\n",
       "\n",
       "    var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n",
       "        'canvas'\n",
       "    ));\n",
       "    rubberband_canvas.setAttribute(\n",
       "        'style',\n",
       "        'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n",
       "    );\n",
       "\n",
       "    // Apply a ponyfill if ResizeObserver is not implemented by browser.\n",
       "    if (this.ResizeObserver === undefined) {\n",
       "        if (window.ResizeObserver !== undefined) {\n",
       "            this.ResizeObserver = window.ResizeObserver;\n",
       "        } else {\n",
       "            var obs = _JSXTOOLS_RESIZE_OBSERVER({});\n",
       "            this.ResizeObserver = obs.ResizeObserver;\n",
       "        }\n",
       "    }\n",
       "\n",
       "    this.resizeObserverInstance = new this.ResizeObserver(function (entries) {\n",
       "        var nentries = entries.length;\n",
       "        for (var i = 0; i < nentries; i++) {\n",
       "            var entry = entries[i];\n",
       "            var width, height;\n",
       "            if (entry.contentBoxSize) {\n",
       "                if (entry.contentBoxSize instanceof Array) {\n",
       "                    // Chrome 84 implements new version of spec.\n",
       "                    width = entry.contentBoxSize[0].inlineSize;\n",
       "                    height = entry.contentBoxSize[0].blockSize;\n",
       "                } else {\n",
       "                    // Firefox implements old version of spec.\n",
       "                    width = entry.contentBoxSize.inlineSize;\n",
       "                    height = entry.contentBoxSize.blockSize;\n",
       "                }\n",
       "            } else {\n",
       "                // Chrome <84 implements even older version of spec.\n",
       "                width = entry.contentRect.width;\n",
       "                height = entry.contentRect.height;\n",
       "            }\n",
       "\n",
       "            // Keep the size of the canvas and rubber band canvas in sync with\n",
       "            // the canvas container.\n",
       "            if (entry.devicePixelContentBoxSize) {\n",
       "                // Chrome 84 implements new version of spec.\n",
       "                canvas.setAttribute(\n",
       "                    'width',\n",
       "                    entry.devicePixelContentBoxSize[0].inlineSize\n",
       "                );\n",
       "                canvas.setAttribute(\n",
       "                    'height',\n",
       "                    entry.devicePixelContentBoxSize[0].blockSize\n",
       "                );\n",
       "            } else {\n",
       "                canvas.setAttribute('width', width * fig.ratio);\n",
       "                canvas.setAttribute('height', height * fig.ratio);\n",
       "            }\n",
       "            canvas.setAttribute(\n",
       "                'style',\n",
       "                'width: ' + width + 'px; height: ' + height + 'px;'\n",
       "            );\n",
       "\n",
       "            rubberband_canvas.setAttribute('width', width);\n",
       "            rubberband_canvas.setAttribute('height', height);\n",
       "\n",
       "            // And update the size in Python. We ignore the initial 0/0 size\n",
       "            // that occurs as the element is placed into the DOM, which should\n",
       "            // otherwise not happen due to the minimum size styling.\n",
       "            if (fig.ws.readyState == 1 && width != 0 && height != 0) {\n",
       "                fig.request_resize(width, height);\n",
       "            }\n",
       "        }\n",
       "    });\n",
       "    this.resizeObserverInstance.observe(canvas_div);\n",
       "\n",
       "    function on_mouse_event_closure(name) {\n",
       "        return function (event) {\n",
       "            return fig.mouse_event(event, name);\n",
       "        };\n",
       "    }\n",
       "\n",
       "    rubberband_canvas.addEventListener(\n",
       "        'mousedown',\n",
       "        on_mouse_event_closure('button_press')\n",
       "    );\n",
       "    rubberband_canvas.addEventListener(\n",
       "        'mouseup',\n",
       "        on_mouse_event_closure('button_release')\n",
       "    );\n",
       "    // Throttle sequential mouse events to 1 every 20ms.\n",
       "    rubberband_canvas.addEventListener(\n",
       "        'mousemove',\n",
       "        on_mouse_event_closure('motion_notify')\n",
       "    );\n",
       "\n",
       "    rubberband_canvas.addEventListener(\n",
       "        'mouseenter',\n",
       "        on_mouse_event_closure('figure_enter')\n",
       "    );\n",
       "    rubberband_canvas.addEventListener(\n",
       "        'mouseleave',\n",
       "        on_mouse_event_closure('figure_leave')\n",
       "    );\n",
       "\n",
       "    canvas_div.addEventListener('wheel', function (event) {\n",
       "        if (event.deltaY < 0) {\n",
       "            event.step = 1;\n",
       "        } else {\n",
       "            event.step = -1;\n",
       "        }\n",
       "        on_mouse_event_closure('scroll')(event);\n",
       "    });\n",
       "\n",
       "    canvas_div.appendChild(canvas);\n",
       "    canvas_div.appendChild(rubberband_canvas);\n",
       "\n",
       "    this.rubberband_context = rubberband_canvas.getContext('2d');\n",
       "    this.rubberband_context.strokeStyle = '#000000';\n",
       "\n",
       "    this._resize_canvas = function (width, height, forward) {\n",
       "        if (forward) {\n",
       "            canvas_div.style.width = width + 'px';\n",
       "            canvas_div.style.height = height + 'px';\n",
       "        }\n",
       "    };\n",
       "\n",
       "    // Disable right mouse context menu.\n",
       "    this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n",
       "        event.preventDefault();\n",
       "        return false;\n",
       "    });\n",
       "\n",
       "    function set_focus() {\n",
       "        canvas.focus();\n",
       "        canvas_div.focus();\n",
       "    }\n",
       "\n",
       "    window.setTimeout(set_focus, 100);\n",
       "};\n",
       "\n",
       "mpl.figure.prototype._init_toolbar = function () {\n",
       "    var fig = this;\n",
       "\n",
       "    var toolbar = document.createElement('div');\n",
       "    toolbar.classList = 'mpl-toolbar';\n",
       "    this.root.appendChild(toolbar);\n",
       "\n",
       "    function on_click_closure(name) {\n",
       "        return function (_event) {\n",
       "            return fig.toolbar_button_onclick(name);\n",
       "        };\n",
       "    }\n",
       "\n",
       "    function on_mouseover_closure(tooltip) {\n",
       "        return function (event) {\n",
       "            if (!event.currentTarget.disabled) {\n",
       "                return fig.toolbar_button_onmouseover(tooltip);\n",
       "            }\n",
       "        };\n",
       "    }\n",
       "\n",
       "    fig.buttons = {};\n",
       "    var buttonGroup = document.createElement('div');\n",
       "    buttonGroup.classList = 'mpl-button-group';\n",
       "    for (var toolbar_ind in mpl.toolbar_items) {\n",
       "        var name = mpl.toolbar_items[toolbar_ind][0];\n",
       "        var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
       "        var image = mpl.toolbar_items[toolbar_ind][2];\n",
       "        var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
       "\n",
       "        if (!name) {\n",
       "            /* Instead of a spacer, we start a new button group. */\n",
       "            if (buttonGroup.hasChildNodes()) {\n",
       "                toolbar.appendChild(buttonGroup);\n",
       "            }\n",
       "            buttonGroup = document.createElement('div');\n",
       "            buttonGroup.classList = 'mpl-button-group';\n",
       "            continue;\n",
       "        }\n",
       "\n",
       "        var button = (fig.buttons[name] = document.createElement('button'));\n",
       "        button.classList = 'mpl-widget';\n",
       "        button.setAttribute('role', 'button');\n",
       "        button.setAttribute('aria-disabled', 'false');\n",
       "        button.addEventListener('click', on_click_closure(method_name));\n",
       "        button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n",
       "\n",
       "        var icon_img = document.createElement('img');\n",
       "        icon_img.src = '_images/' + image + '.png';\n",
       "        icon_img.srcset = '_images/' + image + '_large.png 2x';\n",
       "        icon_img.alt = tooltip;\n",
       "        button.appendChild(icon_img);\n",
       "\n",
       "        buttonGroup.appendChild(button);\n",
       "    }\n",
       "\n",
       "    if (buttonGroup.hasChildNodes()) {\n",
       "        toolbar.appendChild(buttonGroup);\n",
       "    }\n",
       "\n",
       "    var fmt_picker = document.createElement('select');\n",
       "    fmt_picker.classList = 'mpl-widget';\n",
       "    toolbar.appendChild(fmt_picker);\n",
       "    this.format_dropdown = fmt_picker;\n",
       "\n",
       "    for (var ind in mpl.extensions) {\n",
       "        var fmt = mpl.extensions[ind];\n",
       "        var option = document.createElement('option');\n",
       "        option.selected = fmt === mpl.default_extension;\n",
       "        option.innerHTML = fmt;\n",
       "        fmt_picker.appendChild(option);\n",
       "    }\n",
       "\n",
       "    var status_bar = document.createElement('span');\n",
       "    status_bar.classList = 'mpl-message';\n",
       "    toolbar.appendChild(status_bar);\n",
       "    this.message = status_bar;\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n",
       "    // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n",
       "    // which will in turn request a refresh of the image.\n",
       "    this.send_message('resize', { width: x_pixels, height: y_pixels });\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.send_message = function (type, properties) {\n",
       "    properties['type'] = type;\n",
       "    properties['figure_id'] = this.id;\n",
       "    this.ws.send(JSON.stringify(properties));\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.send_draw_message = function () {\n",
       "    if (!this.waiting) {\n",
       "        this.waiting = true;\n",
       "        this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n",
       "    }\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.handle_save = function (fig, _msg) {\n",
       "    var format_dropdown = fig.format_dropdown;\n",
       "    var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n",
       "    fig.ondownload(fig, format);\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.handle_resize = function (fig, msg) {\n",
       "    var size = msg['size'];\n",
       "    if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n",
       "        fig._resize_canvas(size[0], size[1], msg['forward']);\n",
       "        fig.send_message('refresh', {});\n",
       "    }\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n",
       "    var x0 = msg['x0'] / fig.ratio;\n",
       "    var y0 = (fig.canvas.height - msg['y0']) / fig.ratio;\n",
       "    var x1 = msg['x1'] / fig.ratio;\n",
       "    var y1 = (fig.canvas.height - msg['y1']) / fig.ratio;\n",
       "    x0 = Math.floor(x0) + 0.5;\n",
       "    y0 = Math.floor(y0) + 0.5;\n",
       "    x1 = Math.floor(x1) + 0.5;\n",
       "    y1 = Math.floor(y1) + 0.5;\n",
       "    var min_x = Math.min(x0, x1);\n",
       "    var min_y = Math.min(y0, y1);\n",
       "    var width = Math.abs(x1 - x0);\n",
       "    var height = Math.abs(y1 - y0);\n",
       "\n",
       "    fig.rubberband_context.clearRect(\n",
       "        0,\n",
       "        0,\n",
       "        fig.canvas.width / fig.ratio,\n",
       "        fig.canvas.height / fig.ratio\n",
       "    );\n",
       "\n",
       "    fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n",
       "    // Updates the figure title.\n",
       "    fig.header.textContent = msg['label'];\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n",
       "    var cursor = msg['cursor'];\n",
       "    switch (cursor) {\n",
       "        case 0:\n",
       "            cursor = 'pointer';\n",
       "            break;\n",
       "        case 1:\n",
       "            cursor = 'default';\n",
       "            break;\n",
       "        case 2:\n",
       "            cursor = 'crosshair';\n",
       "            break;\n",
       "        case 3:\n",
       "            cursor = 'move';\n",
       "            break;\n",
       "    }\n",
       "    fig.rubberband_canvas.style.cursor = cursor;\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.handle_message = function (fig, msg) {\n",
       "    fig.message.textContent = msg['message'];\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n",
       "    // Request the server to send over a new figure.\n",
       "    fig.send_draw_message();\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n",
       "    fig.image_mode = msg['mode'];\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n",
       "    for (var key in msg) {\n",
       "        if (!(key in fig.buttons)) {\n",
       "            continue;\n",
       "        }\n",
       "        fig.buttons[key].disabled = !msg[key];\n",
       "        fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n",
       "    }\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n",
       "    if (msg['mode'] === 'PAN') {\n",
       "        fig.buttons['Pan'].classList.add('active');\n",
       "        fig.buttons['Zoom'].classList.remove('active');\n",
       "    } else if (msg['mode'] === 'ZOOM') {\n",
       "        fig.buttons['Pan'].classList.remove('active');\n",
       "        fig.buttons['Zoom'].classList.add('active');\n",
       "    } else {\n",
       "        fig.buttons['Pan'].classList.remove('active');\n",
       "        fig.buttons['Zoom'].classList.remove('active');\n",
       "    }\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.updated_canvas_event = function () {\n",
       "    // Called whenever the canvas gets updated.\n",
       "    this.send_message('ack', {});\n",
       "};\n",
       "\n",
       "// A function to construct a web socket function for onmessage handling.\n",
       "// Called in the figure constructor.\n",
       "mpl.figure.prototype._make_on_message_function = function (fig) {\n",
       "    return function socket_on_message(evt) {\n",
       "        if (evt.data instanceof Blob) {\n",
       "            /* FIXME: We get \"Resource interpreted as Image but\n",
       "             * transferred with MIME type text/plain:\" errors on\n",
       "             * Chrome.  But how to set the MIME type?  It doesn't seem\n",
       "             * to be part of the websocket stream */\n",
       "            evt.data.type = 'image/png';\n",
       "\n",
       "            /* Free the memory for the previous frames */\n",
       "            if (fig.imageObj.src) {\n",
       "                (window.URL || window.webkitURL).revokeObjectURL(\n",
       "                    fig.imageObj.src\n",
       "                );\n",
       "            }\n",
       "\n",
       "            fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n",
       "                evt.data\n",
       "            );\n",
       "            fig.updated_canvas_event();\n",
       "            fig.waiting = false;\n",
       "            return;\n",
       "        } else if (\n",
       "            typeof evt.data === 'string' &&\n",
       "            evt.data.slice(0, 21) === 'data:image/png;base64'\n",
       "        ) {\n",
       "            fig.imageObj.src = evt.data;\n",
       "            fig.updated_canvas_event();\n",
       "            fig.waiting = false;\n",
       "            return;\n",
       "        }\n",
       "\n",
       "        var msg = JSON.parse(evt.data);\n",
       "        var msg_type = msg['type'];\n",
       "\n",
       "        // Call the  \"handle_{type}\" callback, which takes\n",
       "        // the figure and JSON message as its only arguments.\n",
       "        try {\n",
       "            var callback = fig['handle_' + msg_type];\n",
       "        } catch (e) {\n",
       "            console.log(\n",
       "                \"No handler for the '\" + msg_type + \"' message type: \",\n",
       "                msg\n",
       "            );\n",
       "            return;\n",
       "        }\n",
       "\n",
       "        if (callback) {\n",
       "            try {\n",
       "                // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n",
       "                callback(fig, msg);\n",
       "            } catch (e) {\n",
       "                console.log(\n",
       "                    \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n",
       "                    e,\n",
       "                    e.stack,\n",
       "                    msg\n",
       "                );\n",
       "            }\n",
       "        }\n",
       "    };\n",
       "};\n",
       "\n",
       "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n",
       "mpl.findpos = function (e) {\n",
       "    //this section is from http://www.quirksmode.org/js/events_properties.html\n",
       "    var targ;\n",
       "    if (!e) {\n",
       "        e = window.event;\n",
       "    }\n",
       "    if (e.target) {\n",
       "        targ = e.target;\n",
       "    } else if (e.srcElement) {\n",
       "        targ = e.srcElement;\n",
       "    }\n",
       "    if (targ.nodeType === 3) {\n",
       "        // defeat Safari bug\n",
       "        targ = targ.parentNode;\n",
       "    }\n",
       "\n",
       "    // pageX,Y are the mouse positions relative to the document\n",
       "    var boundingRect = targ.getBoundingClientRect();\n",
       "    var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n",
       "    var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n",
       "\n",
       "    return { x: x, y: y };\n",
       "};\n",
       "\n",
       "/*\n",
       " * return a copy of an object with only non-object keys\n",
       " * we need this to avoid circular references\n",
       " * http://stackoverflow.com/a/24161582/3208463\n",
       " */\n",
       "function simpleKeys(original) {\n",
       "    return Object.keys(original).reduce(function (obj, key) {\n",
       "        if (typeof original[key] !== 'object') {\n",
       "            obj[key] = original[key];\n",
       "        }\n",
       "        return obj;\n",
       "    }, {});\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.mouse_event = function (event, name) {\n",
       "    var canvas_pos = mpl.findpos(event);\n",
       "\n",
       "    if (name === 'button_press') {\n",
       "        this.canvas.focus();\n",
       "        this.canvas_div.focus();\n",
       "    }\n",
       "\n",
       "    var x = canvas_pos.x * this.ratio;\n",
       "    var y = canvas_pos.y * this.ratio;\n",
       "\n",
       "    this.send_message(name, {\n",
       "        x: x,\n",
       "        y: y,\n",
       "        button: event.button,\n",
       "        step: event.step,\n",
       "        guiEvent: simpleKeys(event),\n",
       "    });\n",
       "\n",
       "    /* This prevents the web browser from automatically changing to\n",
       "     * the text insertion cursor when the button is pressed.  We want\n",
       "     * to control all of the cursor setting manually through the\n",
       "     * 'cursor' event from matplotlib */\n",
       "    event.preventDefault();\n",
       "    return false;\n",
       "};\n",
       "\n",
       "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n",
       "    // Handle any extra behaviour associated with a key event\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.key_event = function (event, name) {\n",
       "    // Prevent repeat events\n",
       "    if (name === 'key_press') {\n",
       "        if (event.which === this._key) {\n",
       "            return;\n",
       "        } else {\n",
       "            this._key = event.which;\n",
       "        }\n",
       "    }\n",
       "    if (name === 'key_release') {\n",
       "        this._key = null;\n",
       "    }\n",
       "\n",
       "    var value = '';\n",
       "    if (event.ctrlKey && event.which !== 17) {\n",
       "        value += 'ctrl+';\n",
       "    }\n",
       "    if (event.altKey && event.which !== 18) {\n",
       "        value += 'alt+';\n",
       "    }\n",
       "    if (event.shiftKey && event.which !== 16) {\n",
       "        value += 'shift+';\n",
       "    }\n",
       "\n",
       "    value += 'k';\n",
       "    value += event.which.toString();\n",
       "\n",
       "    this._key_event_extra(event, name);\n",
       "\n",
       "    this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n",
       "    return false;\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n",
       "    if (name === 'download') {\n",
       "        this.handle_save(this, null);\n",
       "    } else {\n",
       "        this.send_message('toolbar_button', { name: name });\n",
       "    }\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n",
       "    this.message.textContent = tooltip;\n",
       "};\n",
       "\n",
       "///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////\n",
       "// prettier-ignore\n",
       "var _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError(\"Constructor requires 'new' operator\");i.set(this,e)}function h(){throw new TypeError(\"Function is not a constructor\")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line\n",
       "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n",
       "\n",
       "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n",
       "\n",
       "mpl.default_extension = \"png\";/* global mpl */\n",
       "\n",
       "var comm_websocket_adapter = function (comm) {\n",
       "    // Create a \"websocket\"-like object which calls the given IPython comm\n",
       "    // object with the appropriate methods. Currently this is a non binary\n",
       "    // socket, so there is still some room for performance tuning.\n",
       "    var ws = {};\n",
       "\n",
       "    ws.close = function () {\n",
       "        comm.close();\n",
       "    };\n",
       "    ws.send = function (m) {\n",
       "        //console.log('sending', m);\n",
       "        comm.send(m);\n",
       "    };\n",
       "    // Register the callback with on_msg.\n",
       "    comm.on_msg(function (msg) {\n",
       "        //console.log('receiving', msg['content']['data'], msg);\n",
       "        // Pass the mpl event to the overridden (by mpl) onmessage function.\n",
       "        ws.onmessage(msg['content']['data']);\n",
       "    });\n",
       "    return ws;\n",
       "};\n",
       "\n",
       "mpl.mpl_figure_comm = function (comm, msg) {\n",
       "    // This is the function which gets called when the mpl process\n",
       "    // starts-up an IPython Comm through the \"matplotlib\" channel.\n",
       "\n",
       "    var id = msg.content.data.id;\n",
       "    // Get hold of the div created by the display call when the Comm\n",
       "    // socket was opened in Python.\n",
       "    var element = document.getElementById(id);\n",
       "    var ws_proxy = comm_websocket_adapter(comm);\n",
       "\n",
       "    function ondownload(figure, _format) {\n",
       "        window.open(figure.canvas.toDataURL());\n",
       "    }\n",
       "\n",
       "    var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n",
       "\n",
       "    // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n",
       "    // web socket which is closed, not our websocket->open comm proxy.\n",
       "    ws_proxy.onopen();\n",
       "\n",
       "    fig.parent_element = element;\n",
       "    fig.cell_info = mpl.find_output_cell(\"<div id='\" + id + \"'></div>\");\n",
       "    if (!fig.cell_info) {\n",
       "        console.error('Failed to find cell for figure', id, fig);\n",
       "        return;\n",
       "    }\n",
       "    fig.cell_info[0].output_area.element.on(\n",
       "        'cleared',\n",
       "        { fig: fig },\n",
       "        fig._remove_fig_handler\n",
       "    );\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.handle_close = function (fig, msg) {\n",
       "    var width = fig.canvas.width / fig.ratio;\n",
       "    fig.cell_info[0].output_area.element.off(\n",
       "        'cleared',\n",
       "        fig._remove_fig_handler\n",
       "    );\n",
       "    fig.resizeObserverInstance.unobserve(fig.canvas_div);\n",
       "\n",
       "    // Update the output cell to use the data from the current canvas.\n",
       "    fig.push_to_output();\n",
       "    var dataURL = fig.canvas.toDataURL();\n",
       "    // Re-enable the keyboard manager in IPython - without this line, in FF,\n",
       "    // the notebook keyboard shortcuts fail.\n",
       "    IPython.keyboard_manager.enable();\n",
       "    fig.parent_element.innerHTML =\n",
       "        '<img src=\"' + dataURL + '\" width=\"' + width + '\">';\n",
       "    fig.close_ws(fig, msg);\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.close_ws = function (fig, msg) {\n",
       "    fig.send_message('closing', msg);\n",
       "    // fig.ws.close()\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.push_to_output = function (_remove_interactive) {\n",
       "    // Turn the data on the canvas into data in the output cell.\n",
       "    var width = this.canvas.width / this.ratio;\n",
       "    var dataURL = this.canvas.toDataURL();\n",
       "    this.cell_info[1]['text/html'] =\n",
       "        '<img src=\"' + dataURL + '\" width=\"' + width + '\">';\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.updated_canvas_event = function () {\n",
       "    // Tell IPython that the notebook contents must change.\n",
       "    IPython.notebook.set_dirty(true);\n",
       "    this.send_message('ack', {});\n",
       "    var fig = this;\n",
       "    // Wait a second, then push the new image to the DOM so\n",
       "    // that it is saved nicely (might be nice to debounce this).\n",
       "    setTimeout(function () {\n",
       "        fig.push_to_output();\n",
       "    }, 1000);\n",
       "};\n",
       "\n",
       "mpl.figure.prototype._init_toolbar = function () {\n",
       "    var fig = this;\n",
       "\n",
       "    var toolbar = document.createElement('div');\n",
       "    toolbar.classList = 'btn-toolbar';\n",
       "    this.root.appendChild(toolbar);\n",
       "\n",
       "    function on_click_closure(name) {\n",
       "        return function (_event) {\n",
       "            return fig.toolbar_button_onclick(name);\n",
       "        };\n",
       "    }\n",
       "\n",
       "    function on_mouseover_closure(tooltip) {\n",
       "        return function (event) {\n",
       "            if (!event.currentTarget.disabled) {\n",
       "                return fig.toolbar_button_onmouseover(tooltip);\n",
       "            }\n",
       "        };\n",
       "    }\n",
       "\n",
       "    fig.buttons = {};\n",
       "    var buttonGroup = document.createElement('div');\n",
       "    buttonGroup.classList = 'btn-group';\n",
       "    var button;\n",
       "    for (var toolbar_ind in mpl.toolbar_items) {\n",
       "        var name = mpl.toolbar_items[toolbar_ind][0];\n",
       "        var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
       "        var image = mpl.toolbar_items[toolbar_ind][2];\n",
       "        var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
       "\n",
       "        if (!name) {\n",
       "            /* Instead of a spacer, we start a new button group. */\n",
       "            if (buttonGroup.hasChildNodes()) {\n",
       "                toolbar.appendChild(buttonGroup);\n",
       "            }\n",
       "            buttonGroup = document.createElement('div');\n",
       "            buttonGroup.classList = 'btn-group';\n",
       "            continue;\n",
       "        }\n",
       "\n",
       "        button = fig.buttons[name] = document.createElement('button');\n",
       "        button.classList = 'btn btn-default';\n",
       "        button.href = '#';\n",
       "        button.title = name;\n",
       "        button.innerHTML = '<i class=\"fa ' + image + ' fa-lg\"></i>';\n",
       "        button.addEventListener('click', on_click_closure(method_name));\n",
       "        button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n",
       "        buttonGroup.appendChild(button);\n",
       "    }\n",
       "\n",
       "    if (buttonGroup.hasChildNodes()) {\n",
       "        toolbar.appendChild(buttonGroup);\n",
       "    }\n",
       "\n",
       "    // Add the status bar.\n",
       "    var status_bar = document.createElement('span');\n",
       "    status_bar.classList = 'mpl-message pull-right';\n",
       "    toolbar.appendChild(status_bar);\n",
       "    this.message = status_bar;\n",
       "\n",
       "    // Add the close button to the window.\n",
       "    var buttongrp = document.createElement('div');\n",
       "    buttongrp.classList = 'btn-group inline pull-right';\n",
       "    button = document.createElement('button');\n",
       "    button.classList = 'btn btn-mini btn-primary';\n",
       "    button.href = '#';\n",
       "    button.title = 'Stop Interaction';\n",
       "    button.innerHTML = '<i class=\"fa fa-power-off icon-remove icon-large\"></i>';\n",
       "    button.addEventListener('click', function (_evt) {\n",
       "        fig.handle_close(fig, {});\n",
       "    });\n",
       "    button.addEventListener(\n",
       "        'mouseover',\n",
       "        on_mouseover_closure('Stop Interaction')\n",
       "    );\n",
       "    buttongrp.appendChild(button);\n",
       "    var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n",
       "    titlebar.insertBefore(buttongrp, titlebar.firstChild);\n",
       "};\n",
       "\n",
       "mpl.figure.prototype._remove_fig_handler = function (event) {\n",
       "    var fig = event.data.fig;\n",
       "    if (event.target !== this) {\n",
       "        // Ignore bubbled events from children.\n",
       "        return;\n",
       "    }\n",
       "    fig.close_ws(fig, {});\n",
       "};\n",
       "\n",
       "mpl.figure.prototype._root_extra_style = function (el) {\n",
       "    el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n",
       "};\n",
       "\n",
       "mpl.figure.prototype._canvas_extra_style = function (el) {\n",
       "    // this is important to make the div 'focusable\n",
       "    el.setAttribute('tabindex', 0);\n",
       "    // reach out to IPython and tell the keyboard manager to turn it's self\n",
       "    // off when our div gets focus\n",
       "\n",
       "    // location in version 3\n",
       "    if (IPython.notebook.keyboard_manager) {\n",
       "        IPython.notebook.keyboard_manager.register_events(el);\n",
       "    } else {\n",
       "        // location in version 2\n",
       "        IPython.keyboard_manager.register_events(el);\n",
       "    }\n",
       "};\n",
       "\n",
       "mpl.figure.prototype._key_event_extra = function (event, _name) {\n",
       "    var manager = IPython.notebook.keyboard_manager;\n",
       "    if (!manager) {\n",
       "        manager = IPython.keyboard_manager;\n",
       "    }\n",
       "\n",
       "    // Check for shift+enter\n",
       "    if (event.shiftKey && event.which === 13) {\n",
       "        this.canvas_div.blur();\n",
       "        // select the cell after this one\n",
       "        var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n",
       "        IPython.notebook.select(index + 1);\n",
       "    }\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.handle_save = function (fig, _msg) {\n",
       "    fig.ondownload(fig, null);\n",
       "};\n",
       "\n",
       "mpl.find_output_cell = function (html_output) {\n",
       "    // Return the cell and output element which can be found *uniquely* in the notebook.\n",
       "    // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n",
       "    // IPython event is triggered only after the cells have been serialised, which for\n",
       "    // our purposes (turning an active figure into a static one), is too late.\n",
       "    var cells = IPython.notebook.get_cells();\n",
       "    var ncells = cells.length;\n",
       "    for (var i = 0; i < ncells; i++) {\n",
       "        var cell = cells[i];\n",
       "        if (cell.cell_type === 'code') {\n",
       "            for (var j = 0; j < cell.output_area.outputs.length; j++) {\n",
       "                var data = cell.output_area.outputs[j];\n",
       "                if (data.data) {\n",
       "                    // IPython >= 3 moved mimebundle to data attribute of output\n",
       "                    data = data.data;\n",
       "                }\n",
       "                if (data['text/html'] === html_output) {\n",
       "                    return [cell, data, j];\n",
       "                }\n",
       "            }\n",
       "        }\n",
       "    }\n",
       "};\n",
       "\n",
       "// Register the function which deals with the matplotlib target/channel.\n",
       "// The kernel may be null if the page has been refreshed.\n",
       "if (IPython.notebook.kernel !== null) {\n",
       "    IPython.notebook.kernel.comm_manager.register_target(\n",
       "        'matplotlib',\n",
       "        mpl.mpl_figure_comm\n",
       "    );\n",
       "}\n"
      ],
      "text/plain": [
       "<IPython.core.display.Javascript object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<img src=\"\" width=\"700\">"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<matplotlib.legend.Legend at 0x7f5974689ee0>"
      ]
     },
     "execution_count": 78,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fig, ax = plt.subplots(figsize=(7, 4))\n",
    "ax.grid()\n",
    "\n",
    "x = np.arange(0, 4500, 1)\n",
    "ax.set_xlim(0, 4500)\n",
    "ax.set_ylim(-10, 180)\n",
    "ax.plot(x, ir_plot(x, 30, fa.freq, IR_inten), label=\"Harmonic\")\n",
    "ax.plot(x, ir_plot(x, 30, freq_anharm, IR_anharm), label=\"Anharmonic (0 K)\")\n",
    "# ax.plot(x, ir_plot(x, 30, freq_anharm, IRT_anharm), label=\"Anharmonic (2500 K)\")\n",
    "ax.plot(x, ir_plot(x, 30, freq_anharm_gau, IR_anharm_gau), label=\"Anharmonic (Gaussian)\")\n",
    "ax.set_ylabel(\"Molar Absorption Coefficient (L mol$^{-1}$ cm$^{-1}$)\")\n",
    "ax.set_xlabel(\"Vibration Wavenumber (cm$^{-1}$)\")\n",
    "ax.set_title(\"Acetaldehyde ($\\mathsf{CH_3CHO}$) Infared Spectrum (HF/STO-3G)\")\n",
    "ax.legend(loc=\"upper right\")\n",
    "\n",
    "ax.set_ylabel(\"IR Intensity (km mol$^{-1}$)\")\n",
    "ax.legend(loc=\"upper right\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c837dba5",
   "metadata": {},
   "source": [
    "## 文档补充信息"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c34f6996",
   "metadata": {},
   "source": [
    "这份文档的一部分内容与颜文杰有较多讨论，与申同昊有一部分讨论。我也算是对非谐矫正有些好奇，于是尝试搞了一下。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c21939d0",
   "metadata": {},
   "source": [
    "[^Barone.JCP.2005]: Anharmonic Vibrational Properties by a fully automated second-order perturbative approach, V. Barone, *J. Chem. Phys.* **2005**, *122*, 014108, doi: [10.1063/1.1824881](https://doi.org/10.1063/1.1824881).\n",
    "\n",
    "[^Miller.CPL.1990]: Ab initio calculation of anharmonic constants for a transition state, with application to semiclassical transition state tunneling probabilities, W. H. Miller, R. Hernandez, N. C. Handy, D. Jayatilaka, A. Willetts, *Chem. Phys. Lett.* **1990**, *172*, 62-68, doi: [10.1016/0009-2614(90)87217-F](https://doi.org/10.1016/0009-2614(90)87217-F).\n",
    "\n",
    "[^Gauss.JCP.2008]: Quantitative prediction of gas-phase <sup>19</sup>F nuclear magnetic shielding constants, M. E. Harding, M. Lenhart, A. A. Auer, J. Gauss, *J. Chem. Phys.* **2008**, *128*, 244111, doi: [10.1063/1.2943145](https://doi.org/10.1063/1.2943145).\n",
    "\n",
    "[^Bloino.JCP.2012]: A second-order perturbation theory route to vibrational averages and transition properties of molecules: General formulation and application to infrared and vibrational circular dichroism spectroscopies, J. Bloino, V. Barone, *J. Chem. Phys.* **2012**, *136*, 124108, doi: [10.1063/1.3695210](https://doi.org/10.1063/1.3695210).\n",
    "\n",
    "[^Bloino.JPCA.2015]: A VPT2 Route to Near-Infrared Spectroscopy: The Role of Mechanical and Electrical Anharmonicity, *J. Phys. Chem. A* **2015**, *119*, 5269-5287, doi: [10.1021/jp509985u](https://doi.org/10.1021/jp509985u)."
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "编辑元数据",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
